latentcode 0.1.0-alpha.3 → 0.1.0-alpha.7

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.
@@ -7941,7 +7941,7 @@ var require_react_reconciler_development = __commonJS({
7941
7941
  var HostPortal = 4;
7942
7942
  var HostComponent = 5;
7943
7943
  var HostText = 6;
7944
- var Fragment5 = 7;
7944
+ var Fragment6 = 7;
7945
7945
  var Mode = 8;
7946
7946
  var ContextConsumer = 9;
7947
7947
  var ContextProvider = 10;
@@ -8081,7 +8081,7 @@ var require_react_reconciler_development = __commonJS({
8081
8081
  return "DehydratedFragment";
8082
8082
  case ForwardRef:
8083
8083
  return getWrappedName$1(type, type.render, "ForwardRef");
8084
- case Fragment5:
8084
+ case Fragment6:
8085
8085
  return "Fragment";
8086
8086
  case HostComponent:
8087
8087
  return type;
@@ -11215,7 +11215,7 @@ var require_react_reconciler_development = __commonJS({
11215
11215
  }
11216
11216
  }
11217
11217
  function updateFragment2(returnFiber, current2, fragment, lanes, key) {
11218
- if (current2 === null || current2.tag !== Fragment5) {
11218
+ if (current2 === null || current2.tag !== Fragment6) {
11219
11219
  var created = createFiberFromFragment(fragment, returnFiber.mode, lanes, key);
11220
11220
  created.return = returnFiber;
11221
11221
  return created;
@@ -11618,7 +11618,7 @@ var require_react_reconciler_development = __commonJS({
11618
11618
  if (child.key === key) {
11619
11619
  var elementType = element.type;
11620
11620
  if (elementType === REACT_FRAGMENT_TYPE) {
11621
- if (child.tag === Fragment5) {
11621
+ if (child.tag === Fragment6) {
11622
11622
  deleteRemainingChildren(returnFiber, child.sibling);
11623
11623
  var existing = useFiber(child, element.props.children);
11624
11624
  existing.return = returnFiber;
@@ -17109,7 +17109,7 @@ var require_react_reconciler_development = __commonJS({
17109
17109
  var _resolvedProps2 = workInProgress2.elementType === type ? _unresolvedProps2 : resolveDefaultProps(type, _unresolvedProps2);
17110
17110
  return updateForwardRef(current2, workInProgress2, type, _resolvedProps2, renderLanes2);
17111
17111
  }
17112
- case Fragment5:
17112
+ case Fragment6:
17113
17113
  return updateFragment(current2, workInProgress2, renderLanes2);
17114
17114
  case Mode:
17115
17115
  return updateMode(current2, workInProgress2, renderLanes2);
@@ -17546,7 +17546,7 @@ var require_react_reconciler_development = __commonJS({
17546
17546
  case SimpleMemoComponent:
17547
17547
  case FunctionComponent:
17548
17548
  case ForwardRef:
17549
- case Fragment5:
17549
+ case Fragment6:
17550
17550
  case Mode:
17551
17551
  case Profiler:
17552
17552
  case ContextConsumer:
@@ -22314,7 +22314,7 @@ var require_react_reconciler_development = __commonJS({
22314
22314
  return fiber;
22315
22315
  }
22316
22316
  function createFiberFromFragment(elements, mode, lanes, key) {
22317
- var fiber = createFiber(Fragment5, elements, key, mode);
22317
+ var fiber = createFiber(Fragment6, elements, key, mode);
22318
22318
  fiber.lanes = lanes;
22319
22319
  return fiber;
22320
22320
  }
@@ -25333,7 +25333,7 @@ var require_websocket = __commonJS({
25333
25333
  var http = __require("http");
25334
25334
  var net = __require("net");
25335
25335
  var tls = __require("tls");
25336
- var { randomBytes: randomBytes2, createHash } = __require("crypto");
25336
+ var { randomBytes: randomBytes2, createHash: createHash2 } = __require("crypto");
25337
25337
  var { Duplex, Readable } = __require("stream");
25338
25338
  var { URL: URL2 } = __require("url");
25339
25339
  var PerMessageDeflate2 = require_permessage_deflate();
@@ -26019,7 +26019,7 @@ var require_websocket = __commonJS({
26019
26019
  abortHandshake(websocket, socket, "Invalid Upgrade header");
26020
26020
  return;
26021
26021
  }
26022
- const digest = createHash("sha1").update(key + GUID).digest("base64");
26022
+ const digest = createHash2("sha1").update(key + GUID).digest("base64");
26023
26023
  if (res.headers["sec-websocket-accept"] !== digest) {
26024
26024
  abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
26025
26025
  return;
@@ -26388,7 +26388,7 @@ var require_websocket_server = __commonJS({
26388
26388
  var EventEmitter3 = __require("events");
26389
26389
  var http = __require("http");
26390
26390
  var { Duplex } = __require("stream");
26391
- var { createHash } = __require("crypto");
26391
+ var { createHash: createHash2 } = __require("crypto");
26392
26392
  var extension2 = require_extension();
26393
26393
  var PerMessageDeflate2 = require_permessage_deflate();
26394
26394
  var subprotocol2 = require_subprotocol();
@@ -26695,7 +26695,7 @@ var require_websocket_server = __commonJS({
26695
26695
  );
26696
26696
  }
26697
26697
  if (this._state > RUNNING) return abortHandshake(socket, 503);
26698
- const digest = createHash("sha1").update(key + GUID).digest("base64");
26698
+ const digest = createHash2("sha1").update(key + GUID).digest("base64");
26699
26699
  const headers = [
26700
26700
  "HTTP/1.1 101 Switching Protocols",
26701
26701
  "Upgrade: websocket",
@@ -34395,9 +34395,10 @@ import { mkdirSync as mkdirSync2, readFileSync as readFileSync4, writeFileSync a
34395
34395
  import { join as join3 } from "node:path";
34396
34396
 
34397
34397
  // src/ads/config.ts
34398
- import { homedir as homedir2 } from "node:os";
34398
+ import { createHash } from "node:crypto";
34399
+ import { homedir as homedir2, hostname } from "node:os";
34399
34400
  import { join as join2 } from "node:path";
34400
- import { mkdirSync, readFileSync as readFileSync3, writeFileSync } from "node:fs";
34401
+ import { chmodSync, mkdirSync, readFileSync as readFileSync3, writeFileSync } from "node:fs";
34401
34402
  var DEFAULT_SERVER = "https://api.latentprotocol.xyz";
34402
34403
  var AGENT_LATENTCODE = "latentcode";
34403
34404
  function configDir() {
@@ -34421,7 +34422,13 @@ function loadConfig() {
34421
34422
  function saveConfig(data) {
34422
34423
  mkdirSync(configDir(), { recursive: true });
34423
34424
  const next = { ...loadConfig(), ...data };
34424
- writeFileSync(configFile(), JSON.stringify(next, null, 2) + "\n");
34425
+ writeFileSync(configFile(), JSON.stringify(next, null, 2) + "\n", { mode: 384 });
34426
+ if (next.latent_key) {
34427
+ try {
34428
+ chmodSync(configFile(), 384);
34429
+ } catch {
34430
+ }
34431
+ }
34425
34432
  return next;
34426
34433
  }
34427
34434
  function resolveServer(cfg = loadConfig()) {
@@ -34431,10 +34438,10 @@ function resolveWallet(cfg = loadConfig()) {
34431
34438
  const w = cfg.wallet || process.env.ADS_WALLET || "";
34432
34439
  return WALLET_RE.test(w) ? w : "";
34433
34440
  }
34434
- function adsEnabled(cfg = loadConfig()) {
34441
+ function adsEnabled(cfg = loadConfig(), key = "latentcode_ads") {
34435
34442
  const env3 = process.env.ADS_ENABLED;
34436
34443
  if (env3 !== void 0) return !["false", "0", "no"].includes(env3.toLowerCase());
34437
- return cfg.latentcode_ads !== false;
34444
+ return cfg[key] !== false;
34438
34445
  }
34439
34446
  function deviceId() {
34440
34447
  try {
@@ -34444,6 +34451,12 @@ function deviceId() {
34444
34451
  }
34445
34452
  return "";
34446
34453
  }
34454
+ function deviceKeyId() {
34455
+ const cred = deviceId();
34456
+ if (cred) return cred.split(".")[0];
34457
+ return createHash("sha256").update(`${hostname()}
34458
+ ${homedir2()}`).digest("hex").slice(0, 32);
34459
+ }
34447
34460
  async function ensureDeviceCredential(server) {
34448
34461
  const current = deviceId();
34449
34462
  if (current) return current;
@@ -34833,6 +34846,7 @@ function classifyPrompt(prompt, cwd2 = process.cwd()) {
34833
34846
  var MIN_VISIBLE_MS = 1e4;
34834
34847
  var ROTATE_MS = 1e4;
34835
34848
  var HOLD_MS = 27e4;
34849
+ var ACTIVE_MS = 6e4;
34836
34850
  function safeUrl(raw) {
34837
34851
  return raw && isSafeUrl(raw) ? new URL(raw).toString() : "";
34838
34852
  }
@@ -34862,10 +34876,14 @@ var AdController = class {
34862
34876
  billed = false;
34863
34877
  lastTick = 0;
34864
34878
  fetching = false;
34879
+ /** Generation of the request in flight; a stale one never blocks a new turn. */
34880
+ fetchingGen = -1;
34865
34881
  generation = 0;
34866
34882
  context = "general";
34867
34883
  impressions = 0;
34868
34884
  sessionEarned = 0;
34885
+ adIndex = 0;
34886
+ lastActivity = 0;
34869
34887
  listeners = /* @__PURE__ */ new Set();
34870
34888
  /** Cached for useSyncExternalStore — must be referentially stable between emits. */
34871
34889
  snap = null;
@@ -34877,6 +34895,7 @@ var AdController = class {
34877
34895
  minVisibleMs: opts.minVisibleMs ?? MIN_VISIBLE_MS,
34878
34896
  rotateMs: opts.rotateMs ?? ROTATE_MS,
34879
34897
  holdMs: opts.holdMs ?? HOLD_MS,
34898
+ activeMs: opts.activeMs ?? ACTIVE_MS,
34880
34899
  classify: opts.classify ?? ((p, cwd2) => classifyPrompt(p, cwd2))
34881
34900
  };
34882
34901
  opts.focus.onChange(() => this.emit());
@@ -34907,7 +34926,9 @@ var AdController = class {
34907
34926
  if (this.snap) return this.snap;
34908
34927
  return this.snap = {
34909
34928
  status: this.status,
34910
- current: this.working ? this.current : null,
34929
+ current: this.current,
34930
+ adIndex: this.adIndex,
34931
+ idle: !this.working,
34911
34932
  visibleMs: this.visibleMs,
34912
34933
  billed: this.billed,
34913
34934
  focusTracked: this.o.focus.known,
@@ -34916,24 +34937,30 @@ var AdController = class {
34916
34937
  context: this.context
34917
34938
  };
34918
34939
  }
34940
+ /** The user typed or pasted: idle dwell may count for the next ACTIVE_MS. */
34941
+ noteActivity() {
34942
+ this.lastActivity = this.o.now();
34943
+ }
34919
34944
  /** Called on execution start/end. `prompt` is classified locally, never sent. */
34920
34945
  setWorking(working, prompt = "") {
34921
34946
  if (working === this.working) return;
34922
34947
  this.working = working;
34923
34948
  this.lastTick = this.o.now();
34949
+ this.lastActivity = this.lastTick;
34924
34950
  if (working) {
34925
34951
  this.context = this.o.classify(prompt, this.o.cwd);
34926
- if (!this.holding()) {
34927
- this.clear();
34928
- void this.fetchNext();
34929
- }
34930
- } else if (this.billed || !this.current) {
34952
+ if (this.current && !this.billed && !this.holding()) this.clear();
34953
+ if (!this.holding()) void this.fetchNext();
34954
+ } else if (!this.current) {
34931
34955
  this.clear();
34932
34956
  } else {
34933
34957
  this.generation += 1;
34934
34958
  }
34935
34959
  this.emit();
34936
34960
  }
34961
+ attentive(now) {
34962
+ return this.o.focus.focused && (this.working || now - this.lastActivity < this.o.activeMs);
34963
+ }
34937
34964
  /** An un-billed ad that may still be shown and billed. */
34938
34965
  holding() {
34939
34966
  return !!this.current && !this.billed && this.o.now() - this.current.fetchedAt < this.o.holdMs;
@@ -34943,13 +34970,22 @@ var AdController = class {
34943
34970
  const now = this.o.now();
34944
34971
  const dt = Math.max(0, now - this.lastTick);
34945
34972
  this.lastTick = now;
34946
- if (!this.working || !this.current) return;
34973
+ if (!this.current) return;
34947
34974
  if (!this.billed && !this.holding()) {
34948
34975
  this.clear();
34949
- void this.fetchNext();
34976
+ if (this.working) void this.fetchNext();
34977
+ this.emit();
34978
+ return;
34979
+ }
34980
+ if (!this.working && this.billed && now - this.current.fetchedAt >= this.o.holdMs) {
34981
+ this.clear();
34982
+ this.emit();
34950
34983
  return;
34951
34984
  }
34952
- if (this.o.focus.focused) this.visibleMs += dt;
34985
+ if (!this.billed && this.attentive(now)) {
34986
+ this.visibleMs += dt;
34987
+ this.emit();
34988
+ }
34953
34989
  if (!this.billed && this.visibleMs >= this.o.minVisibleMs) {
34954
34990
  this.billed = true;
34955
34991
  const shown = this.current;
@@ -34969,14 +35005,13 @@ var AdController = class {
34969
35005
  });
34970
35006
  this.emit();
34971
35007
  }
34972
- if (this.billed && now - this.shownAt >= this.o.rotateMs && !this.fetching) {
35008
+ if (this.working && this.billed && now - this.shownAt >= this.o.rotateMs && !this.fetching) {
34973
35009
  void this.fetchNext();
34974
35010
  }
34975
35011
  }
34976
35012
  /** User asked to open the ad (keyboard): the tracked link, or null. The server counts the click on redirect. */
34977
35013
  click() {
34978
- const ad = this.working ? this.current : null;
34979
- return ad?.link || null;
35014
+ return this.current?.link || null;
34980
35015
  }
34981
35016
  clear() {
34982
35017
  this.generation += 1;
@@ -34985,9 +35020,10 @@ var AdController = class {
34985
35020
  this.billed = false;
34986
35021
  }
34987
35022
  async fetchNext() {
34988
- if (this.status !== "ok" || this.fetching) return;
34989
- this.fetching = true;
34990
35023
  const gen = this.generation;
35024
+ if (this.status !== "ok" || this.fetching && this.fetchingGen === gen) return;
35025
+ this.fetching = true;
35026
+ this.fetchingGen = gen;
34991
35027
  try {
34992
35028
  const ad = await this.o.api.request({ wallet: this.o.wallet, context: this.context, sessionId: this.o.sessionId });
34993
35029
  if (gen !== this.generation || !this.working || this.status !== "ok") return;
@@ -34997,13 +35033,14 @@ var AdController = class {
34997
35033
  return;
34998
35034
  }
34999
35035
  this.current = display;
35036
+ this.adIndex += 1;
35000
35037
  this.shownAt = this.o.now();
35001
35038
  this.lastTick = this.shownAt;
35002
35039
  this.visibleMs = 0;
35003
35040
  this.billed = false;
35004
35041
  this.emit();
35005
35042
  } finally {
35006
- this.fetching = false;
35043
+ if (this.fetchingGen === gen) this.fetching = false;
35007
35044
  }
35008
35045
  }
35009
35046
  emit() {
@@ -35092,7 +35129,9 @@ function recordServerResult(ok, now = Date.now()) {
35092
35129
 
35093
35130
  // src/ads/api.ts
35094
35131
  var SURFACE_WORKING_BAR = "status_line";
35095
- function httpAdApi(server = resolveServer()) {
35132
+ function httpAdApi(server = resolveServer(), identity = {}) {
35133
+ const agent = identity.agent ?? AGENT_LATENTCODE;
35134
+ const surface = identity.surface ?? SURFACE_WORKING_BAR;
35096
35135
  return {
35097
35136
  server,
35098
35137
  async request({ wallet, context, sessionId }) {
@@ -35105,9 +35144,9 @@ function httpAdApi(server = resolveServer()) {
35105
35144
  headers: { "Content-Type": "application/json" },
35106
35145
  body: JSON.stringify({
35107
35146
  user_wallet: wallet,
35108
- agent: AGENT_LATENTCODE,
35147
+ agent,
35109
35148
  context: context.slice(0, 100),
35110
- surface: SURFACE_WORKING_BAR,
35149
+ surface,
35111
35150
  tags: context ? [context] : [],
35112
35151
  session_id: sessionId,
35113
35152
  device_id: device
@@ -35134,8 +35173,8 @@ function httpAdApi(server = resolveServer()) {
35134
35173
  ad_id: ad.ad_id,
35135
35174
  user_wallet: wallet,
35136
35175
  token: ad.impression_token ?? "",
35137
- agent: AGENT_LATENTCODE,
35138
- surface: SURFACE_WORKING_BAR,
35176
+ agent,
35177
+ surface,
35139
35178
  context,
35140
35179
  device_id: device,
35141
35180
  event_uuid: eventUuid,
@@ -35155,11 +35194,37 @@ function httpAdApi(server = resolveServer()) {
35155
35194
  return "error";
35156
35195
  }
35157
35196
  },
35197
+ async creditQuote() {
35198
+ try {
35199
+ const res = await fetch(`${server}/credit/quote`, { signal: AbortSignal.timeout(4e3) });
35200
+ if (!res.ok) return null;
35201
+ const q = await res.json();
35202
+ return {
35203
+ bonus: Number(q.bonus ?? 1),
35204
+ buybackPrice: Number(q.sell_price ?? q.buyback_price ?? 0),
35205
+ buybackEnabled: Boolean(q.buyback_enabled)
35206
+ };
35207
+ } catch {
35208
+ return null;
35209
+ }
35210
+ },
35158
35211
  async balance(wallet) {
35159
35212
  try {
35160
35213
  const res = await fetch(`${server}/earnings/${wallet}`, { signal: AbortSignal.timeout(4e3) });
35161
35214
  if (!res.ok) return null;
35162
- return Number((await res.json()).balance ?? 0);
35215
+ const e = await res.json();
35216
+ return Number(e.credits ?? e.balance ?? 0);
35217
+ } catch {
35218
+ return null;
35219
+ }
35220
+ },
35221
+ async creditSummary(wallet) {
35222
+ try {
35223
+ const res = await fetch(`${server}/credit/${wallet}/summary`, { signal: AbortSignal.timeout(4e3) });
35224
+ if (!res.ok) return null;
35225
+ const c = await res.json();
35226
+ const mode = c.mode === "auto_sell" || c.mode === "auto_list" ? c.mode : "keep";
35227
+ return { credits: Number(c.credits ?? 0), mode, bonus: Number(c.bonus ?? 1), sellPrice: Number(c.sell_price ?? 0) };
35163
35228
  } catch {
35164
35229
  return null;
35165
35230
  }
@@ -35167,6 +35232,191 @@ function httpAdApi(server = resolveServer()) {
35167
35232
  };
35168
35233
  }
35169
35234
 
35235
+ // src/engine/customProvider.ts
35236
+ import { existsSync as existsSync5, mkdirSync as mkdirSync4, readFileSync as readFileSync7, renameSync, writeFileSync as writeFileSync4, copyFileSync } from "node:fs";
35237
+ import { homedir as homedir3 } from "node:os";
35238
+ import { join as join6 } from "node:path";
35239
+ var KIND_PACKAGE = {
35240
+ openai: "@opencode/ai/providers/openai-compatible",
35241
+ anthropic: "@opencode/ai/providers/anthropic-compatible"
35242
+ };
35243
+ var KIND_LABEL = {
35244
+ openai: "OpenAI-compatible",
35245
+ anthropic: "Anthropic-compatible"
35246
+ };
35247
+ var CONFIG_FILES = ["opencode.json", "opencode.jsonc"];
35248
+ function slugify(name) {
35249
+ return name.normalize("NFKD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40);
35250
+ }
35251
+ function providerIdFor(name, taken, custom) {
35252
+ const base = slugify(name) || "custom";
35253
+ if (custom.has(base) || !taken.has(base)) return base;
35254
+ for (let i = 0; ; i++) {
35255
+ const id = i === 0 ? `${base}-custom` : `${base}-custom-${i + 1}`;
35256
+ if (custom.has(id) || !taken.has(id)) return id;
35257
+ }
35258
+ }
35259
+ function normalizeBaseURL(raw) {
35260
+ const s2 = raw.trim();
35261
+ let u;
35262
+ try {
35263
+ u = new URL(s2);
35264
+ } catch {
35265
+ throw new Error("That is not a URL. Example: https://api.example.com/v1");
35266
+ }
35267
+ if (u.protocol !== "https:" && u.protocol !== "http:") throw new Error("The base URL must start with https:// or http://");
35268
+ if (u.search || u.hash) throw new Error("Leave out the query string \u2014 just the base URL, e.g. https://api.example.com/v1");
35269
+ return u.toString().replace(/\/+$/, "");
35270
+ }
35271
+ function parseModelList(raw) {
35272
+ const seen = /* @__PURE__ */ new Set();
35273
+ for (const part of raw.split(/[\s,]+/)) {
35274
+ const id = part.trim();
35275
+ if (id) seen.add(id);
35276
+ }
35277
+ return [...seen];
35278
+ }
35279
+ function providerEntry(input) {
35280
+ const models = {};
35281
+ for (const id of input.models) models[id] = { name: id };
35282
+ return {
35283
+ name: input.name.trim(),
35284
+ package: KIND_PACKAGE[input.kind],
35285
+ settings: { baseURL: input.baseURL },
35286
+ models
35287
+ };
35288
+ }
35289
+ function parseJsonc(text) {
35290
+ let out = "";
35291
+ let hadComments = false;
35292
+ let i = 0;
35293
+ while (i < text.length) {
35294
+ const ch = text[i];
35295
+ if (ch === '"') {
35296
+ let j = i + 1;
35297
+ while (j < text.length && text[j] !== '"') j += text[j] === "\\" ? 2 : 1;
35298
+ out += text.slice(i, j + 1);
35299
+ i = j + 1;
35300
+ } else if (ch === "/" && text[i + 1] === "/") {
35301
+ hadComments = true;
35302
+ while (i < text.length && text[i] !== "\n") i++;
35303
+ } else if (ch === "/" && text[i + 1] === "*") {
35304
+ hadComments = true;
35305
+ const end2 = text.indexOf("*/", i + 2);
35306
+ i = end2 < 0 ? text.length : end2 + 2;
35307
+ } else {
35308
+ if (ch === "}" || ch === "]") {
35309
+ const m = out.match(/,\s*$/);
35310
+ if (m) out = out.slice(0, out.length - m[0].length) + m[0].slice(1);
35311
+ }
35312
+ out += ch;
35313
+ i++;
35314
+ }
35315
+ }
35316
+ return { value: out.trim() ? JSON.parse(out) : {}, hadComments };
35317
+ }
35318
+ function mergeProvider(existing, id, entry, defaultModel) {
35319
+ const { value, hadComments } = existing ? parseJsonc(existing) : { value: {}, hadComments: false };
35320
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("The engine config file is not a JSON object.");
35321
+ const config = value;
35322
+ const providers = config.providers;
35323
+ if (providers !== void 0 && (typeof providers !== "object" || providers === null || Array.isArray(providers))) {
35324
+ throw new Error('The engine config has a "providers" value that is not an object.');
35325
+ }
35326
+ const next = { ...config, providers: { ...providers ?? {}, [id]: entry } };
35327
+ if (!("$schema" in next)) next.$schema = "https://opencode.ai/config.json";
35328
+ if (defaultModel && !next.model) next.model = defaultModel;
35329
+ return { text: JSON.stringify(next, null, 2) + "\n", hadComments };
35330
+ }
35331
+ function configuredProviderIds(text) {
35332
+ if (!text) return /* @__PURE__ */ new Set();
35333
+ try {
35334
+ const v = parseJsonc(text).value;
35335
+ return new Set(Object.keys(v?.providers ?? {}));
35336
+ } catch {
35337
+ return /* @__PURE__ */ new Set();
35338
+ }
35339
+ }
35340
+ function defaultConfigDir(env3 = process.env) {
35341
+ return join6(env3.XDG_CONFIG_HOME || join6(homedir3(), ".config"), "opencode");
35342
+ }
35343
+ function configFileIn(dir, exists = existsSync5) {
35344
+ const present = CONFIG_FILES.map((f) => join6(dir, f)).filter(exists);
35345
+ return present.at(-1) ?? join6(dir, "opencode.json");
35346
+ }
35347
+ function readConfigText(file) {
35348
+ try {
35349
+ return readFileSync7(file, "utf8");
35350
+ } catch {
35351
+ return null;
35352
+ }
35353
+ }
35354
+ function writeProviderConfig(file, id, input, defaultModel) {
35355
+ const existing = readConfigText(file);
35356
+ const { text, hadComments } = mergeProvider(existing, id, providerEntry(input), defaultModel);
35357
+ mkdirSync4(join6(file, ".."), { recursive: true });
35358
+ let backup;
35359
+ if (existing !== null && hadComments) {
35360
+ backup = file + ".bak";
35361
+ copyFileSync(file, backup);
35362
+ }
35363
+ const tmp = `${file}.${process.pid}.tmp`;
35364
+ writeFileSync4(tmp, text);
35365
+ renameSync(tmp, file);
35366
+ return { file, backup };
35367
+ }
35368
+ async function discoverModels(kind, baseURL, key, timeoutMs = 1e4) {
35369
+ const headers = kind === "anthropic" ? { "anthropic-version": "2023-06-01", ...key ? { "x-api-key": key } : {} } : key ? { authorization: `Bearer ${key}` } : {};
35370
+ const res = await fetch(baseURL + "/models", { headers, signal: AbortSignal.timeout(timeoutMs) });
35371
+ if (!res.ok) throw new Error(`${baseURL}/models answered ${res.status}`);
35372
+ return parseModelsResponse(await res.json());
35373
+ }
35374
+ function parseModelsResponse(body) {
35375
+ const data = body?.data ?? body?.models;
35376
+ if (!Array.isArray(data)) throw new Error("The /models answer has no model list.");
35377
+ return parseModelList(
35378
+ data.map((m) => typeof m === "string" ? m : typeof m === "object" && m ? String(m.id ?? "") : "").join(" ")
35379
+ );
35380
+ }
35381
+
35382
+ // src/engine/latentProvider.ts
35383
+ var LATENT_PROVIDER_ID = "latent";
35384
+ var LATENT_KEY_RE = /^lk_[A-Za-z0-9_-]{20,}$/;
35385
+ function latentBaseURL(server) {
35386
+ return server.replace(/\/+$/, "") + "/v1";
35387
+ }
35388
+ async function connectLatentKey(engine, server, key, discover = discoverModels, suggested) {
35389
+ const k = key.trim();
35390
+ if (!LATENT_KEY_RE.test(k)) throw new Error("That is not a Latent Key \u2014 it starts with lk_. Get one at latentprotocol.xyz/app/earn.");
35391
+ const baseURL = latentBaseURL(server);
35392
+ let models;
35393
+ try {
35394
+ models = await discover("openai", baseURL, k);
35395
+ } catch (e) {
35396
+ const why = e instanceof Error ? e.message : String(e);
35397
+ throw new Error(/ 401/.test(why) ? "The ad server does not know this key \u2014 it may have been rotated." : `Could not reach Latent (${why}).`);
35398
+ }
35399
+ if (!models.length) throw new Error("Latent lists no models right now. Try again in a minute.");
35400
+ const file = configFileIn(await engine.configDir() ?? defaultConfigDir());
35401
+ const pick = suggested && models.includes(suggested) ? suggested : void 0;
35402
+ const defaultModel = pick ? `${LATENT_PROVIDER_ID}/${pick}` : void 0;
35403
+ const written = writeProviderConfig(file, LATENT_PROVIDER_ID, { name: "Latent", kind: "openai", baseURL, models }, defaultModel);
35404
+ await engine.reloadConfig();
35405
+ await engine.waitForIntegration(LATENT_PROVIDER_ID);
35406
+ await engine.connectKey(LATENT_PROVIDER_ID, k);
35407
+ return { id: LATENT_PROVIDER_ID, models, file: written.file, backup: written.backup, defaultModel };
35408
+ }
35409
+ async function connectPendingLatentKey(engine, server, store, discover = discoverModels) {
35410
+ const cfg = store.load();
35411
+ if (!cfg.latent_key) return null;
35412
+ const res = await connectLatentKey(engine, server, cfg.latent_key, discover, cfg.latent_default_model);
35413
+ store.save({ latent_key: void 0, latent_default_model: void 0 });
35414
+ return res;
35415
+ }
35416
+ function credits(balanceUsd, bonus) {
35417
+ return balanceUsd * (bonus > 0 ? bonus : 1);
35418
+ }
35419
+
35170
35420
  // src/ui/theme.ts
35171
35421
  var C = {
35172
35422
  accent: "#A78BFA",
@@ -35269,20 +35519,31 @@ async function boot(args, focus, report) {
35269
35519
  return { value, detail: `opencode${bin.version ? " " + bin.version : ""} \xB7 ${where} \xB7 private, this session only` };
35270
35520
  });
35271
35521
  const models = new ModelStore();
35522
+ let latentStart;
35523
+ let latentNote = "";
35272
35524
  const [catalog, commands] = await step("providers", async () => {
35525
+ try {
35526
+ const res = await connectPendingLatentKey(engine, resolveServer(), { load: loadConfig, save: (p) => void saveConfig(p) });
35527
+ if (res) {
35528
+ latentStart = res.defaultModel;
35529
+ latentNote = "Latent connected";
35530
+ }
35531
+ } catch (e) {
35532
+ latentNote = `Latent not connected yet (${firstLine(e)})`;
35533
+ }
35273
35534
  const value = await Promise.all([engine.catalog(), engine.commands()]);
35274
35535
  const c = value[0];
35275
35536
  const verified = c.models.filter((m) => models.get(m.key)?.status === "ok").length;
35276
35537
  return {
35277
35538
  value,
35278
35539
  status: c.models.length ? "ok" : "warn",
35279
- detail: c.models.length ? `${listNames(c.providers.map((p) => p.name))} \xB7 ${c.models.length} models${verified ? `, ${verified} verified` : ""}` : "none connected yet \u2014 /connect to add one"
35540
+ detail: (c.models.length ? `${listNames(c.providers.map((p) => p.name))} \xB7 ${c.models.length} models${verified ? `, ${verified} verified` : ""}` : "none connected yet \u2014 /connect to add one") + (latentNote ? ` \xB7 ${latentNote}` : "")
35280
35541
  };
35281
35542
  });
35282
35543
  const permissions = args.auto ? [] : SAFE_PERMISSIONS;
35283
35544
  let startNotice;
35284
35545
  const session = await step("model", async () => {
35285
- let start = args.model;
35546
+ let start = args.model ?? (latentStart ? parseKey(latentStart) ?? void 0 : void 0);
35286
35547
  if (!start) {
35287
35548
  const def = await engine.defaultModel();
35288
35549
  const defKey = def ? `${def.providerID}/${def.id}` : null;
@@ -35573,48 +35834,144 @@ function reduce(state, ev, now = Date.now()) {
35573
35834
  }
35574
35835
  }
35575
35836
 
35576
- // src/ui/SponsoredLine.tsx
35837
+ // src/ui/StatusPanel.tsx
35577
35838
  var import_jsx_runtime = __toESM(require_jsx_runtime(), 1);
35578
- var MAX_BARE_URL = 60;
35579
- var SHAPE = linkShape();
35580
- function SponsoredLine({ ad, billed, shape = SHAPE }) {
35581
- const linked = !!ad.link && shape !== "plain";
35582
- const showUrl = !!ad.shownUrl && shape !== "osc8" && ad.shownUrl.length <= MAX_BARE_URL;
35583
- const badge = adBadge(ad.title || ad.body);
35584
- const copy = /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Text, { children: [
35585
- /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Text, { bold: true, underline: linked, children: ad.title || ad.body }),
35586
- ad.title && ad.body ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Text, { color: C.muted, children: [
35587
- " \u2014 ",
35588
- ad.body
35589
- ] }) : null
35839
+ var fmtTok = (n) => n >= 1e3 ? `${(n / 1e3).toFixed(1)}k` : String(n);
35840
+ var fmtUsd2 = (n) => `$${n.toFixed(n !== 0 && Math.abs(n) < 0.01 ? 4 : 2)}`;
35841
+ function Rule({ width }) {
35842
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Text, { color: C.border, children: "\u2500".repeat(Math.max(0, width)) });
35843
+ }
35844
+ function Progress({ ms, of, billed }) {
35845
+ if (billed) return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Text, { color: C.ok, children: [
35846
+ G.ok,
35847
+ " view counted"
35590
35848
  ] });
35591
- return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Box_default, { justifyContent: "space-between", children: [
35592
- /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Text, { wrap: "truncate-end", children: [
35593
- /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Text, { color: C.earn, children: [
35594
- G.earn,
35595
- " Sponsored"
35596
- ] }),
35597
- /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Text, { color: C.faint, children: [
35598
- " ",
35599
- G.thin,
35600
- " "
35849
+ const n = 10;
35850
+ const filled = Math.min(n, Math.floor(ms / of * n));
35851
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Text, { children: [
35852
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Text, { color: C.earn, children: "\u25B0".repeat(filled) }),
35853
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Text, { color: C.border, children: "\u25B1".repeat(n - filled) }),
35854
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Text, { color: C.faint, children: [
35855
+ " ",
35856
+ Math.floor(ms / 1e3),
35857
+ "s / ",
35858
+ Math.round(of / 1e3),
35859
+ "s"
35860
+ ] })
35861
+ ] });
35862
+ }
35863
+ function StatusPanel(p) {
35864
+ const inner = p.width - 4;
35865
+ const frame = p.working ? C.accent : C.border;
35866
+ const name = p.model || "no model";
35867
+ const prov = p.provider ? ` \xB7 ${p.provider}` : "";
35868
+ const variant = p.variant ? ` ${p.variant}` : "";
35869
+ const usage2 = [p.tokens ? `${fmtTok(p.tokens)} tok` : "", p.cost ? fmtUsd2(p.cost) : ""].filter(Boolean).join(" \xB7 ");
35870
+ const rightLen = usage2 ? usage2.length + 2 : 0;
35871
+ const leftBudget = p.width - 9 - rightLen;
35872
+ const leftText = clip(`${name}${variant}${prov}`, Math.max(8, leftBudget));
35873
+ const fill = Math.max(1, p.width - 8 - leftText.length - rightLen);
35874
+ const top = /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Text, { wrap: "truncate-end", children: [
35875
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Text, { color: frame, children: "\u256D\u2500 " }),
35876
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Text, { color: p.latent ? C.earn : p.working ? C.accent : C.ok, children: G.dot }),
35877
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Text, { children: " " }),
35878
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Text, { bold: true, color: C.text, children: leftText.slice(0, name.length) }),
35879
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Text, { color: C.accent2, children: leftText.slice(name.length, name.length + variant.length) }),
35880
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Text, { color: C.muted, children: leftText.slice(name.length + variant.length) }),
35881
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Text, { color: frame, children: [
35882
+ " ",
35883
+ "\u2500".repeat(fill)
35884
+ ] }),
35885
+ usage2 ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Text, { color: C.faint, children: [
35886
+ " ",
35887
+ usage2,
35888
+ " "
35889
+ ] }) : null,
35890
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Text, { color: frame, children: "\u2500\u256E" })
35891
+ ] });
35892
+ const earnings = p.earn === "ok" ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Text, { wrap: "truncate-end", children: [
35893
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Text, { color: C.earn, children: [
35894
+ G.earn,
35895
+ " "
35896
+ ] }),
35897
+ p.balance != null ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [
35898
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Text, { color: C.earn, bold: true, children: [
35899
+ p.balance.toFixed(3),
35900
+ " cr"
35601
35901
  ] }),
35602
- /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Text, { backgroundColor: badge.color, color: "#111827", bold: true, children: ` ${badge.letter} ` }),
35603
- /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Text, { children: " " }),
35604
- linked ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Transform, { transform: (out) => osc8(out, ad.link), children: copy }) : copy,
35605
- showUrl ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Text, { color: C.accent2, children: [
35606
- " \xB7 ",
35607
- ad.shownUrl
35608
- ] }) : null,
35609
- ad.link ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Text, { color: C.faint, children: [
35610
- " \xB7 ctrl+o ",
35611
- ad.ctaText
35612
- ] }) : null
35902
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Text, { color: C.faint, children: " \xB7 " })
35903
+ ] }) : null,
35904
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Text, { color: C.earn, children: [
35905
+ "+",
35906
+ p.sessionCredits.toFixed(3)
35613
35907
  ] }),
35614
- billed && ad.earn > 0 ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Text, { color: C.earn, children: [
35615
- " +$",
35616
- ad.earn.toFixed(4)
35617
- ] }) : null
35908
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Text, { color: C.faint, children: [
35909
+ inner >= 84 ? " this session" : "",
35910
+ " \xB7 ",
35911
+ p.views,
35912
+ " view",
35913
+ p.views === 1 ? "" : "s"
35914
+ ] })
35915
+ ] }) : p.earn === "disabled" ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Text, { color: C.faint, children: [
35916
+ G.earn,
35917
+ " Earn off \xB7 /ads on"
35918
+ ] }) : /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Text, { color: C.warn, children: [
35919
+ G.earn,
35920
+ " /login to start earning"
35921
+ ] });
35922
+ const ad = p.earn === "ok" ? p.ad : null;
35923
+ let body;
35924
+ if (ad) {
35925
+ const badge = adBadge(ad.title || ad.body);
35926
+ const cta = ad.link ? `${ad.ctaText || "Open"} ${G.arrow}` : "";
35927
+ const ctaLen = cta ? cta.length + 8 : 0;
35928
+ const brand = ad.title || ad.body;
35929
+ const rest = ad.title && ad.body ? ` \u2014 ${ad.body}` : "";
35930
+ const copyText = clip(brand + rest, Math.max(10, inner - 4 - ctaLen));
35931
+ const copy = /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Text, { children: [
35932
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Text, { bold: true, underline: !!ad.link && p.osc8Links, children: copyText.slice(0, brand.length) }),
35933
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Text, { color: C.muted, children: copyText.slice(brand.length) })
35934
+ ] });
35935
+ body = /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [
35936
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Box_default, { justifyContent: "space-between", children: [
35937
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Text, { color: C.faint, bold: true, children: "SPONSORED" }),
35938
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Text, { color: C.faint, children: [
35939
+ "AD \xB7 ",
35940
+ String(p.adIndex ?? 1).padStart(2, "0")
35941
+ ] })
35942
+ ] }),
35943
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Box_default, { justifyContent: "space-between", children: [
35944
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Text, { wrap: "truncate-end", children: [
35945
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Text, { backgroundColor: badge.color, color: "#111827", bold: true, children: ` ${badge.letter} ` }),
35946
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Text, { children: " " }),
35947
+ p.osc8Links && ad.link ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Transform, { transform: (o) => osc8(o, ad.link), children: copy }) : copy
35948
+ ] }),
35949
+ cta ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Text, { children: [
35950
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Text, { color: C.accent2, bold: true, children: cta }),
35951
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Text, { color: C.faint, children: " ctrl+o" })
35952
+ ] }) : null
35953
+ ] }),
35954
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Rule, { width: inner }),
35955
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Box_default, { justifyContent: "space-between", children: [
35956
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Text, { wrap: "truncate-end", children: [
35957
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Progress, { ms: p.visibleMs ?? 0, of: p.minVisibleMs ?? 1e4, billed: !!p.billed }),
35958
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Text, { color: C.faint, children: " \xB7 Powered by Latent Ads" })
35959
+ ] }),
35960
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Box_default, { flexShrink: 0, marginLeft: 2, children: earnings })
35961
+ ] })
35962
+ ] });
35963
+ } else {
35964
+ body = /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Box_default, { justifyContent: "space-between", children: [
35965
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Text, { color: C.faint, wrap: "truncate-end", children: [
35966
+ p.wallet ? p.wallet : "",
35967
+ p.earn === "ok" ? `${p.wallet ? " \xB7 " : ""}ads show while the agent works` : ""
35968
+ ] }),
35969
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Box_default, { flexShrink: 0, marginLeft: 2, children: earnings })
35970
+ ] });
35971
+ }
35972
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Box_default, { flexDirection: "column", width: p.width, children: [
35973
+ top,
35974
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Box_default, { flexDirection: "column", borderStyle: "round", borderTop: false, borderColor: frame, paddingX: 1, width: p.width, children: body })
35618
35975
  ] });
35619
35976
  }
35620
35977
 
@@ -36023,7 +36380,9 @@ var COMMANDS = [
36023
36380
  { name: "providers", desc: "Connected providers and what each one offers", group: "Models" },
36024
36381
  { name: "connect", args: "[provider]", desc: "Connect a provider: API key or account sign-in", group: "Models" },
36025
36382
  { name: "login", desc: "Connect the wallet Earn mode pays into", group: "Earn", aliases: ["wallet"] },
36026
- { name: "earn", desc: "Earnings: this session and your unpaid balance", group: "Earn" },
36383
+ { name: "earn", desc: "Earnings: this session and your Latent Credit", group: "Earn" },
36384
+ { name: "credits", desc: "Latent Credit: balance, bonus, mode, sell price", group: "Earn", aliases: ["credit"] },
36385
+ { name: "key", args: "lk_\u2026", desc: "Use your Latent Key as a provider \u2014 earnings become model usage", group: "Earn" },
36027
36386
  { name: "ads", args: "on|off", desc: "Turn Earn mode (the sponsored line) on or off", group: "Earn" },
36028
36387
  { name: "new", desc: "Start a fresh session", group: "Session" },
36029
36388
  { name: "compact", desc: "Summarise the conversation to free up context", group: "Session" },
@@ -36460,154 +36819,6 @@ function ModelPicker(p) {
36460
36819
 
36461
36820
  // src/ui/panels/ProviderPanel.tsx
36462
36821
  var import_react24 = __toESM(require_react(), 1);
36463
-
36464
- // src/engine/customProvider.ts
36465
- import { existsSync as existsSync5, mkdirSync as mkdirSync4, readFileSync as readFileSync7, renameSync, writeFileSync as writeFileSync4, copyFileSync } from "node:fs";
36466
- import { homedir as homedir3 } from "node:os";
36467
- import { join as join6 } from "node:path";
36468
- var KIND_PACKAGE = {
36469
- openai: "@opencode/ai/providers/openai-compatible",
36470
- anthropic: "@opencode/ai/providers/anthropic-compatible"
36471
- };
36472
- var KIND_LABEL = {
36473
- openai: "OpenAI-compatible",
36474
- anthropic: "Anthropic-compatible"
36475
- };
36476
- var CONFIG_FILES = ["opencode.json", "opencode.jsonc"];
36477
- function slugify(name) {
36478
- return name.normalize("NFKD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40);
36479
- }
36480
- function providerIdFor(name, taken, custom) {
36481
- const base = slugify(name) || "custom";
36482
- if (custom.has(base) || !taken.has(base)) return base;
36483
- for (let i = 0; ; i++) {
36484
- const id = i === 0 ? `${base}-custom` : `${base}-custom-${i + 1}`;
36485
- if (custom.has(id) || !taken.has(id)) return id;
36486
- }
36487
- }
36488
- function normalizeBaseURL(raw) {
36489
- const s2 = raw.trim();
36490
- let u;
36491
- try {
36492
- u = new URL(s2);
36493
- } catch {
36494
- throw new Error("That is not a URL. Example: https://api.example.com/v1");
36495
- }
36496
- if (u.protocol !== "https:" && u.protocol !== "http:") throw new Error("The base URL must start with https:// or http://");
36497
- if (u.search || u.hash) throw new Error("Leave out the query string \u2014 just the base URL, e.g. https://api.example.com/v1");
36498
- return u.toString().replace(/\/+$/, "");
36499
- }
36500
- function parseModelList(raw) {
36501
- const seen = /* @__PURE__ */ new Set();
36502
- for (const part of raw.split(/[\s,]+/)) {
36503
- const id = part.trim();
36504
- if (id) seen.add(id);
36505
- }
36506
- return [...seen];
36507
- }
36508
- function providerEntry(input) {
36509
- const models = {};
36510
- for (const id of input.models) models[id] = { name: id };
36511
- return {
36512
- name: input.name.trim(),
36513
- package: KIND_PACKAGE[input.kind],
36514
- settings: { baseURL: input.baseURL },
36515
- models
36516
- };
36517
- }
36518
- function parseJsonc(text) {
36519
- let out = "";
36520
- let hadComments = false;
36521
- let i = 0;
36522
- while (i < text.length) {
36523
- const ch = text[i];
36524
- if (ch === '"') {
36525
- let j = i + 1;
36526
- while (j < text.length && text[j] !== '"') j += text[j] === "\\" ? 2 : 1;
36527
- out += text.slice(i, j + 1);
36528
- i = j + 1;
36529
- } else if (ch === "/" && text[i + 1] === "/") {
36530
- hadComments = true;
36531
- while (i < text.length && text[i] !== "\n") i++;
36532
- } else if (ch === "/" && text[i + 1] === "*") {
36533
- hadComments = true;
36534
- const end2 = text.indexOf("*/", i + 2);
36535
- i = end2 < 0 ? text.length : end2 + 2;
36536
- } else {
36537
- if (ch === "}" || ch === "]") {
36538
- const m = out.match(/,\s*$/);
36539
- if (m) out = out.slice(0, out.length - m[0].length) + m[0].slice(1);
36540
- }
36541
- out += ch;
36542
- i++;
36543
- }
36544
- }
36545
- return { value: out.trim() ? JSON.parse(out) : {}, hadComments };
36546
- }
36547
- function mergeProvider(existing, id, entry) {
36548
- const { value, hadComments } = existing ? parseJsonc(existing) : { value: {}, hadComments: false };
36549
- if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("The engine config file is not a JSON object.");
36550
- const config = value;
36551
- const providers = config.providers;
36552
- if (providers !== void 0 && (typeof providers !== "object" || providers === null || Array.isArray(providers))) {
36553
- throw new Error('The engine config has a "providers" value that is not an object.');
36554
- }
36555
- const next = { ...config, providers: { ...providers ?? {}, [id]: entry } };
36556
- if (!("$schema" in next)) next.$schema = "https://opencode.ai/config.json";
36557
- return { text: JSON.stringify(next, null, 2) + "\n", hadComments };
36558
- }
36559
- function configuredProviderIds(text) {
36560
- if (!text) return /* @__PURE__ */ new Set();
36561
- try {
36562
- const v = parseJsonc(text).value;
36563
- return new Set(Object.keys(v?.providers ?? {}));
36564
- } catch {
36565
- return /* @__PURE__ */ new Set();
36566
- }
36567
- }
36568
- function defaultConfigDir(env3 = process.env) {
36569
- return join6(env3.XDG_CONFIG_HOME || join6(homedir3(), ".config"), "opencode");
36570
- }
36571
- function configFileIn(dir, exists = existsSync5) {
36572
- const present = CONFIG_FILES.map((f) => join6(dir, f)).filter(exists);
36573
- return present.at(-1) ?? join6(dir, "opencode.json");
36574
- }
36575
- function readConfigText(file) {
36576
- try {
36577
- return readFileSync7(file, "utf8");
36578
- } catch {
36579
- return null;
36580
- }
36581
- }
36582
- function writeProviderConfig(file, id, input) {
36583
- const existing = readConfigText(file);
36584
- const { text, hadComments } = mergeProvider(existing, id, providerEntry(input));
36585
- mkdirSync4(join6(file, ".."), { recursive: true });
36586
- let backup;
36587
- if (existing !== null && hadComments) {
36588
- backup = file + ".bak";
36589
- copyFileSync(file, backup);
36590
- }
36591
- const tmp = `${file}.${process.pid}.tmp`;
36592
- writeFileSync4(tmp, text);
36593
- renameSync(tmp, file);
36594
- return { file, backup };
36595
- }
36596
- async function discoverModels(kind, baseURL, key, timeoutMs = 1e4) {
36597
- const headers = kind === "anthropic" ? { "anthropic-version": "2023-06-01", ...key ? { "x-api-key": key } : {} } : key ? { authorization: `Bearer ${key}` } : {};
36598
- const res = await fetch(baseURL + "/models", { headers, signal: AbortSignal.timeout(timeoutMs) });
36599
- if (!res.ok) throw new Error(`${baseURL}/models answered ${res.status}`);
36600
- return parseModelsResponse(await res.json());
36601
- }
36602
- function parseModelsResponse(body) {
36603
- const data = body?.data ?? body?.models;
36604
- if (!Array.isArray(data)) throw new Error("The /models answer has no model list.");
36605
- return parseModelList(
36606
- data.map((m) => typeof m === "string" ? m : typeof m === "object" && m ? String(m.id ?? "") : "").join(" ")
36607
- );
36608
- }
36609
-
36610
- // src/ui/panels/ProviderPanel.tsx
36611
36822
  var import_jsx_runtime5 = __toESM(require_jsx_runtime(), 1);
36612
36823
  var usable = (i) => i.methods.filter((m) => m.type === "key" || m.type === "oauth");
36613
36824
  var needsForm = (m) => "form" in m && Array.isArray(m.form) && m.form.some((f) => !f.hidden && f.required);
@@ -37387,6 +37598,25 @@ async function pollDeviceToken(appId, deviceCode, opts) {
37387
37598
  }
37388
37599
  throw new Error("Auth link timed out \u2014 run `latentcode login` again.");
37389
37600
  }
37601
+ async function issueLoginKey(server, accessToken, deviceId2, fetchImpl = fetch) {
37602
+ let res;
37603
+ try {
37604
+ res = await fetchImpl(`${trimServer(server)}/auth/latent-key`, {
37605
+ method: "POST",
37606
+ headers: { "Content-Type": "application/json" },
37607
+ body: JSON.stringify({ access_token: accessToken, device_id: deviceId2 })
37608
+ });
37609
+ } catch {
37610
+ return null;
37611
+ }
37612
+ if ([404, 405, 503].includes(res.status)) return null;
37613
+ const body = await readJson(res);
37614
+ if (!res.ok) {
37615
+ throw new Error(typeof body.detail === "string" ? body.detail : `latent-key HTTP ${res.status}`);
37616
+ }
37617
+ if (!body.wallet || !body.privy_user_id || !body.key) return null;
37618
+ return { wallet: body.wallet, privy_user_id: body.privy_user_id, key: body.key, default_model: body.default_model ?? null };
37619
+ }
37390
37620
  async function resolveSession(server, accessToken, fetchImpl = fetch) {
37391
37621
  const res = await fetchImpl(`${trimServer(server)}/auth/session`, {
37392
37622
  method: "POST",
@@ -37439,12 +37669,24 @@ You can still connect an address you control: latentcode login --wallet 0x\u2026
37439
37669
  sleep: deps2.sleep,
37440
37670
  now: deps2.now
37441
37671
  });
37442
- const earner = await resolveSession(deps2.server, tokens.access_token, deps2.fetchImpl);
37672
+ const withKey = deps2.deviceId ? await issueLoginKey(deps2.server, tokens.access_token, deps2.deviceId(), deps2.fetchImpl) : null;
37673
+ const earner = withKey ?? await resolveSession(deps2.server, tokens.access_token, deps2.fetchImpl);
37443
37674
  if (!WALLET_RE.test(earner.wallet)) throw new Error("The server returned an invalid wallet address.");
37444
37675
  const prev = deps2.load().wallet;
37445
- deps2.save({ wallet: earner.wallet, privy_user_id: earner.privy_user_id, auth: "privy" });
37676
+ deps2.save({
37677
+ wallet: earner.wallet,
37678
+ privy_user_id: earner.privy_user_id,
37679
+ auth: "privy",
37680
+ ...withKey ? { latent_key: withKey.key, latent_default_model: withKey.default_model ?? void 0 } : {}
37681
+ });
37446
37682
  deps2.log(`Signed in. Earn mode pays into ${short(earner.wallet)}.`);
37447
- return { wallet: earner.wallet, method: "privy", replaced: prev && prev !== earner.wallet ? prev : void 0 };
37683
+ if (withKey) deps2.log("Latent provider ready: your earnings pay for model usage.");
37684
+ return {
37685
+ wallet: earner.wallet,
37686
+ method: "privy",
37687
+ replaced: prev && prev !== earner.wallet ? prev : void 0,
37688
+ latentKey: Boolean(withKey)
37689
+ };
37448
37690
  }
37449
37691
 
37450
37692
  // src/ui/panels/WalletPanel.tsx
@@ -37456,6 +37698,7 @@ var deps = (server, extra) => ({
37456
37698
  open: openUrl,
37457
37699
  load: loadConfig,
37458
37700
  save: (patch) => void saveConfig(patch),
37701
+ deviceId: deviceKeyId,
37459
37702
  ...extra
37460
37703
  });
37461
37704
  function WalletPanel(p) {
@@ -37495,7 +37738,7 @@ function Menu(p) {
37495
37738
  color: C.earn,
37496
37739
  footer: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Hints, { items: [["\u2191\u2193", "move"], ["enter", "continue"], ["esc", "close"]] }),
37497
37740
  children: /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, children: [
37498
- /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { color: C.muted, wrap: "wrap", children: p.wallet ? "Earn mode pays into this wallet. Connect a different one:" : "Earn mode pays you in USDC while the agent works. Connect the wallet it should pay into:" }),
37741
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { color: C.muted, wrap: "wrap", children: p.wallet ? "Earn mode pays into this wallet. Connect a different one:" : "Earn mode pays you in Latent Credit while the agent works \u2014 model usage, or USDG when you sell. Connect the wallet it should pay into:" }),
37499
37742
  /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Box_default, { flexDirection: "column", marginTop: 1, children: options.map((o, i) => /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(Text, { children: [
37500
37743
  /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(Text, { color: C.earn, children: [
37501
37744
  i === sel ? G.prompt : " ",
@@ -37589,7 +37832,7 @@ function Address(p) {
37589
37832
  color: C.earn,
37590
37833
  footer: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Hints, { items: [["enter", "save"], ["esc", "back"]] }),
37591
37834
  children: /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, children: [
37592
- /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { color: C.muted, children: "Earnings are paid in USDC to this address. Use one you control." }),
37835
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { color: C.muted, children: "Credit is earned on this address; sales pay USDG here. Use one you control." }),
37593
37836
  /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(Box_default, { marginTop: 1, children: [
37594
37837
  /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(Text, { color: C.earn, children: [
37595
37838
  G.earn,
@@ -37619,6 +37862,8 @@ function Done2(p) {
37619
37862
 
37620
37863
  // src/ui/App.tsx
37621
37864
  var import_jsx_runtime7 = __toESM(require_jsx_runtime(), 1);
37865
+ var DASHBOARD = "latentprotocol.xyz/app";
37866
+ var MODE = { keep: "keep and spend (bonus)", auto_sell: "sell automatically for USDG", auto_list: "list at my price" };
37622
37867
  var notice = (text, tone = "info") => ({
37623
37868
  type: "latentcode.notice",
37624
37869
  created: Date.now(),
@@ -37736,6 +37981,7 @@ function HelpPanel({ width, commands, onClose }) {
37736
37981
  /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Text, { color: C.faint, wrap: "wrap", children: `Privacy: ads never enter the model's context or its answers. The only thing sent to the ad server is a coarse category (for example "backend"), worked out on this machine.` }) })
37737
37982
  ] });
37738
37983
  }
37984
+ var LINKS_OSC8 = linkShape() === "osc8";
37739
37985
  function App2(props) {
37740
37986
  const { engine, controller, api, cwd: cwd2, version } = props;
37741
37987
  const { exit } = use_app_default();
@@ -37787,11 +38033,15 @@ function App2(props) {
37787
38033
  const say = (text, tone = "info") => dispatch(notice(text, tone));
37788
38034
  const statusOf = (key) => store.get(key)?.status ?? "unknown";
37789
38035
  const modelName = (key) => catalog.models.find((m) => m.key === key)?.name ?? key;
38036
+ const [bonus, setBonus] = (0, import_react26.useState)(1);
38037
+ (0, import_react26.useEffect)(() => {
38038
+ void api.creditQuote().then((q) => q && setBonus(q.bonus));
38039
+ }, [api]);
37790
38040
  props.summary.current = {
37791
38041
  turns: state.turns,
37792
38042
  tokens: state.tokens.input + state.tokens.output,
37793
38043
  cost: state.cost,
37794
- earned: ad.sessionEarned,
38044
+ earned: credits(ad.sessionEarned, bonus),
37795
38045
  impressions: ad.impressions
37796
38046
  };
37797
38047
  (0, import_react26.useEffect)(() => {
@@ -37809,14 +38059,27 @@ function App2(props) {
37809
38059
  (0, import_react26.useEffect)(() => {
37810
38060
  controller.setWorking(state.working, lastPrompt.current);
37811
38061
  }, [state.working, controller]);
38062
+ const lingering = !state.working && !!ad.current;
37812
38063
  (0, import_react26.useEffect)(() => {
37813
- if (!state.working) return;
37814
- const t = setInterval(() => {
37815
- controller.tick();
37816
- tick((f) => f + 1);
37817
- }, 250);
38064
+ if (!state.working && !lingering) return;
38065
+ const t = setInterval(
38066
+ () => {
38067
+ controller.tick();
38068
+ if (state.working) tick((f) => f + 1);
38069
+ },
38070
+ state.working ? 250 : 1e3
38071
+ );
37818
38072
  return () => clearInterval(t);
37819
- }, [state.working, controller]);
38073
+ }, [state.working, lingering, controller]);
38074
+ const [balance, setBalance] = (0, import_react26.useState)(null);
38075
+ (0, import_react26.useEffect)(() => {
38076
+ if (!wallet || state.working) return;
38077
+ let live2 = true;
38078
+ void api.creditSummary(wallet).then((c) => live2 && setBalance(c ? c.credits : null));
38079
+ return () => {
38080
+ live2 = false;
38081
+ };
38082
+ }, [api, wallet, state.working, ad.impressions]);
37820
38083
  (0, import_react26.useEffect)(() => setPermAt(0), [state.permissions[0]?.id]);
37821
38084
  (0, import_react26.useEffect)(() => {
37822
38085
  if (!quitArmed) return;
@@ -37862,6 +38125,19 @@ function App2(props) {
37862
38125
  function changeWallet(next) {
37863
38126
  setWallet(next);
37864
38127
  controller.setWallet(next);
38128
+ void connectLoginKey();
38129
+ }
38130
+ async function connectLoginKey() {
38131
+ try {
38132
+ const res = await connectPendingLatentKey(engine, props.server, { load: loadConfig, save: (p) => void saveConfig(p) });
38133
+ if (!res) return;
38134
+ const next = await reloadCatalog();
38135
+ const m = res.defaultModel ? next.models.find((x) => x.key === res.defaultModel) : void 0;
38136
+ if (m) await pickModel(m, "");
38137
+ say(`Latent connected: ${res.models.length} models, paid from your earnings.${m ? "" : " Pick one with /model latent."}`, "ok");
38138
+ } catch (e) {
38139
+ say(`Latent not connected: ${e instanceof Error ? e.message : String(e)}. Try /key lk_\u2026 with a key from the dashboard.`, "warn");
38140
+ }
37865
38141
  }
37866
38142
  async function runCommand(line) {
37867
38143
  const { name, arg } = parseCommandLine(line);
@@ -37913,13 +38189,54 @@ function App2(props) {
37913
38189
  say("No wallet connected yet. /login takes a minute and you start earning right away.", "warn");
37914
38190
  return;
37915
38191
  }
37916
- const bal = await api.balance(wallet);
38192
+ const c = await api.creditSummary(wallet);
38193
+ const hasLatent = catalog.providers.some((p) => p.id === LATENT_PROVIDER_ID);
37917
38194
  say(
37918
- `This session: ${ad.impressions} sponsored view${ad.impressions === 1 ? "" : "s"} \u2248 $${ad.sessionEarned.toFixed(4)} (indicative)
37919
- Wallet ${shortWallet(wallet)} \xB7 unpaid balance ${bal === null ? "unavailable right now" : "$" + bal.toFixed(4)}`
38195
+ `This session: ${ad.impressions} sponsored view${ad.impressions === 1 ? "" : "s"} \u2248 ${credits(ad.sessionEarned, bonus).toFixed(3)} credits (indicative)
38196
+ Wallet ${shortWallet(wallet)} \xB7 ${c === null ? "balance unavailable right now" : `${c.credits.toFixed(2)} Latent Credit ($1 of model usage each)`}` + (c ? `
38197
+ Mode: ${MODE[c.mode]} \u2014 change it at ${DASHBOARD}/settings` : "") + (hasLatent ? "" : `
38198
+ Spend it here: /login connects the Latent provider (or /key lk_\u2026 with a key from ${DASHBOARD}/earn).`)
37920
38199
  );
37921
38200
  return;
37922
38201
  }
38202
+ case "credits": {
38203
+ if (!wallet) {
38204
+ say("No wallet connected yet. /login first.", "warn");
38205
+ return;
38206
+ }
38207
+ const [c, q] = await Promise.all([api.creditSummary(wallet), api.creditQuote()]);
38208
+ if (!c) {
38209
+ say("Credit balance unavailable right now.", "warn");
38210
+ return;
38211
+ }
38212
+ say(
38213
+ [
38214
+ `Latent Credit ${c.credits.toFixed(2)} credits \xB7 $1 of model usage at list price each`,
38215
+ `Bonus ${c.bonus}\xD7 \u2014 every $1 earned from ads becomes ${c.bonus} credits`,
38216
+ `Mode ${MODE[c.mode]}`,
38217
+ q?.buybackEnabled ? `Sell now ${q.buybackPrice.toFixed(2)} USDG per credit, paid on Robinhood Chain` : `Sell now opens soon`,
38218
+ `Change it ${DASHBOARD}/settings \xB7 sell or list at ${DASHBOARD}/earn \xB7 buy at ${DASHBOARD}/credits`
38219
+ ].join("\n")
38220
+ );
38221
+ return;
38222
+ }
38223
+ case "key": {
38224
+ const k = arg.trim();
38225
+ if (!k) {
38226
+ say("/login connects the Latent provider for you. Or paste a key from latentprotocol.xyz/app/earn: /key lk_\u2026");
38227
+ return;
38228
+ }
38229
+ say("Connecting your Latent Key\u2026");
38230
+ try {
38231
+ const res = await connectLatentKey(engine, props.server, k);
38232
+ await reloadCatalog();
38233
+ const note = res.backup ? ` (Comments in ${res.file} could not be kept; the original is at ${res.backup}.)` : "";
38234
+ say(`Latent connected: ${res.models.length} models, paid from your earnings. Pick one with /model latent.${note}`, "ok");
38235
+ } catch (e) {
38236
+ say(e instanceof Error ? e.message : String(e), "warn");
38237
+ }
38238
+ return;
38239
+ }
37923
38240
  case "status": {
37924
38241
  const prov = catalog.providers.map((p) => p.name).join(", ");
37925
38242
  say(
@@ -37927,7 +38244,7 @@ Wallet ${shortWallet(wallet)} \xB7 unpaid balance ${bal === null ? "unavailable
37927
38244
  `Model ${describeModel(state.model, catalog)}${state.variant ? ` \xB7 effort ${state.variant}` : ""}`,
37928
38245
  `Providers ${prov || "none"}`,
37929
38246
  `Session ${state.turns} turn${state.turns === 1 ? "" : "s"} \xB7 ${fmtTokens(state.tokens.input)} in / ${fmtTokens(state.tokens.output)} out${state.cost ? ` \xB7 ${fmtUsd(state.cost)}` : ""}`,
37930
- `Earn ${ad.status === "disabled" ? "off" : wallet ? `on \xB7 ${shortWallet(wallet)} \xB7 \u2248 $${ad.sessionEarned.toFixed(4)} this session` : "no wallet \u2014 /login"}`,
38247
+ `Earn ${ad.status === "disabled" ? "off" : wallet ? `on \xB7 ${shortWallet(wallet)} \xB7 \u2248 ${credits(ad.sessionEarned, bonus).toFixed(3)} credits this session` : "no wallet \u2014 /login"}`,
37931
38248
  `Safety ${props.permissions.length ? "asks before shell commands and file changes" : "--auto (no confirmation)"}`
37932
38249
  ].join("\n")
37933
38250
  );
@@ -37973,9 +38290,13 @@ Wallet ${shortWallet(wallet)} \xB7 unpaid balance ${bal === null ? "unavailable
37973
38290
  const matches = overlay || perm || paletteHidden ? [] : matchCommands(editor.text, allCommands);
37974
38291
  const paletteOpen = matches.length > 0 && !(matches.length === 1 && "/" + matches[0].name === editor.text && !matches[0].args);
37975
38292
  const paletteSel = Math.min(paletteAt, Math.max(0, matches.length - 1));
37976
- usePaste((text) => setEditor(insert(editorRef.current, text.replace(/\n+$/, ""))), overlay === null && !perm);
38293
+ usePaste((text) => {
38294
+ controller.noteActivity();
38295
+ setEditor(insert(editorRef.current, text.replace(/\n+$/, "")));
38296
+ }, overlay === null && !perm);
37977
38297
  use_input_default(
37978
38298
  (ch, key) => {
38299
+ controller.noteActivity();
37979
38300
  if (perm) {
37980
38301
  const decisions = ["once", "always", "reject"];
37981
38302
  const reply = (d) => void engine.replyPermission(sessionID, perm.id, d).catch(fail);
@@ -38035,28 +38356,25 @@ Wallet ${shortWallet(wallet)} \xB7 unpaid balance ${bal === null ? "unavailable
38035
38356
  /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Static, { items: [header, ...done.map((it) => ({ id: it.id, it }))], children: (entry) => "it" in entry ? /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(ItemView, { item: entry.it, live: false, cwd: cwd2, width, maxLines }, entry.id) : /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(BootCard, { steps: props.bootSteps, version, cwd: cwd2, width, ready: true }, entry.id) }),
38036
38357
  live.map((it) => /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(ItemView, { item: it, live: true, cwd: cwd2, width, maxLines }, it.id)),
38037
38358
  perm ? /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(PermissionPrompt, { perm, selected: permAt, cwd: cwd2, width }) : null,
38038
- state.working ? /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(Box_default, { marginTop: 1, flexDirection: "column", width, children: [
38039
- /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(Text, { wrap: "truncate-end", children: [
38040
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Spinner, {}),
38041
- /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(Text, { children: [
38042
- " ",
38043
- activityLabel(state),
38044
- "\u2026"
38045
- ] }),
38046
- /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(Text, { color: C.faint, children: [
38047
- " ",
38048
- elapsed,
38049
- "s \xB7 ",
38050
- G.up,
38051
- fmtTokens(state.tokens.input),
38052
- " ",
38053
- G.down,
38054
- fmtTokens(state.tokens.output),
38055
- " \xB7 esc to interrupt"
38056
- ] })
38359
+ state.working ? /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Box_default, { marginTop: 1, flexDirection: "column", width, children: /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(Text, { wrap: "truncate-end", children: [
38360
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Spinner, {}),
38361
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(Text, { children: [
38362
+ " ",
38363
+ activityLabel(state),
38364
+ "\u2026"
38057
38365
  ] }),
38058
- ad.current ? /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(SponsoredLine, { ad: ad.current, billed: ad.billed }) : null
38059
- ] }) : null,
38366
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(Text, { color: C.faint, children: [
38367
+ " ",
38368
+ elapsed,
38369
+ "s \xB7 ",
38370
+ G.up,
38371
+ fmtTokens(state.tokens.input),
38372
+ " ",
38373
+ G.down,
38374
+ fmtTokens(state.tokens.output),
38375
+ " \xB7 esc to interrupt"
38376
+ ] })
38377
+ ] }) }) : null,
38060
38378
  overlay?.t === "model" ? /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
38061
38379
  ModelPicker,
38062
38380
  {
@@ -38134,44 +38452,29 @@ Wallet ${shortWallet(wallet)} \xB7 unpaid balance ${bal === null ? "unavailable
38134
38452
  /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Hints, { items: [["\u2191\u2193", "move"], ["tab", "complete"], ["enter", "run"], ["esc", "dismiss"]] })
38135
38453
  ] }) : null
38136
38454
  ] }) : null,
38137
- paletteOpen || leaving ? null : /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(Box_default, { width, justifyContent: "space-between", paddingX: 1, children: [
38138
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Text, { wrap: "truncate-end", children: quitArmed ? /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Text, { color: C.warn, children: "Press ctrl+c again to quit" }) : /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(import_jsx_runtime7.Fragment, { children: [
38139
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Text, { color: current ? C.text : C.warn, children: current?.name ?? (state.model || "no model") }),
38140
- state.variant ? /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(Text, { color: C.accent2, children: [
38141
- " ",
38142
- state.variant
38143
- ] }) : null,
38144
- provider ? /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(Text, { color: C.faint, children: [
38145
- " \xB7 ",
38146
- provider.name
38147
- ] }) : null,
38148
- state.tokens.input + state.tokens.output ? /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(Text, { color: C.faint, children: [
38149
- " ",
38150
- "\xB7 ",
38151
- fmtTokens(state.tokens.input + state.tokens.output),
38152
- " tok",
38153
- state.cost ? ` \xB7 ${fmtUsd(state.cost)}` : ""
38154
- ] }) : null
38155
- ] }) }),
38156
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Text, { wrap: "truncate-end", children: ad.status === "ok" ? /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(Text, { color: C.earn, children: [
38157
- G.earn,
38158
- " $",
38159
- ad.sessionEarned.toFixed(4),
38160
- " earned",
38161
- /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(Text, { color: C.faint, children: [
38162
- " \xB7 ",
38163
- ad.impressions,
38164
- " view",
38165
- ad.impressions === 1 ? "" : "s"
38166
- ] })
38167
- ] }) : ad.status === "disabled" ? /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(Text, { color: C.faint, children: [
38168
- G.earn,
38169
- " Earn off \xB7 /ads on"
38170
- ] }) : /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(Text, { color: C.warn, children: [
38171
- G.earn,
38172
- " /login to start earning"
38173
- ] }) })
38174
- ] })
38455
+ paletteOpen || leaving ? null : quitArmed ? /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Box_default, { paddingX: 1, width, children: /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Text, { color: C.warn, children: "Press ctrl+c again to quit" }) }) : /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
38456
+ StatusPanel,
38457
+ {
38458
+ width,
38459
+ model: current?.name ?? state.model,
38460
+ variant: state.variant,
38461
+ provider: provider?.name,
38462
+ latent: (current?.providerID ?? parseKey(state.model)?.providerID) === "latent",
38463
+ working: state.working,
38464
+ tokens: state.tokens.input + state.tokens.output,
38465
+ cost: state.cost,
38466
+ earn: ad.status,
38467
+ ad: ad.current,
38468
+ adIndex: ad.adIndex,
38469
+ visibleMs: ad.visibleMs,
38470
+ billed: ad.billed,
38471
+ balance,
38472
+ sessionCredits: credits(ad.sessionEarned, bonus),
38473
+ views: ad.impressions,
38474
+ wallet: shortWallet(wallet),
38475
+ osc8Links: LINKS_OSC8
38476
+ }
38477
+ )
38175
38478
  ] });
38176
38479
  }
38177
38480
 
@@ -38427,7 +38730,7 @@ function row(mark, label2, value, width = 10) {
38427
38730
 
38428
38731
  // src/index.tsx
38429
38732
  var import_jsx_runtime9 = __toESM(require_jsx_runtime(), 1);
38430
- var VERSION = "0.1.0-alpha.3";
38733
+ var VERSION = "0.1.0-alpha.7";
38431
38734
  var usage = () => `${logo()}
38432
38735
  ${a.dim(`v${VERSION} \xB7 terminal coding agent. Bring your own model access; earn while it works.`)}
38433
38736
 
@@ -38487,7 +38790,8 @@ function loginDeps() {
38487
38790
  log: (l) => process.stdout.write(styleLoginLine(l) + "\n"),
38488
38791
  open: openUrl,
38489
38792
  load: loadConfig,
38490
- save: (patch) => void saveConfig(patch)
38793
+ save: (patch) => void saveConfig(patch),
38794
+ deviceId: deviceKeyId
38491
38795
  };
38492
38796
  }
38493
38797
  function styleLoginLine(l) {
@@ -38535,7 +38839,7 @@ async function status() {
38535
38839
  if (wallet) {
38536
38840
  const bal = await httpAdApi(server).balance(wallet);
38537
38841
  lines.push(
38538
- row(a.earn("\u25C6"), "Balance", bal === null ? a.dim("unavailable (ad server unreachable)") : `${a.earn("$" + bal.toFixed(4))} unpaid`)
38842
+ row(a.earn("\u25C6"), "Credit", bal === null ? a.dim("unavailable (ad server unreachable)") : `${a.earn(bal.toFixed(2) + " credits")} ${a.dim("($1 of model usage each)")}`)
38539
38843
  );
38540
38844
  }
38541
38845
  process.stdout.write(lines.join("\n") + "\n");
@@ -38544,7 +38848,7 @@ function goodbye(s2) {
38544
38848
  const parts = s2.turns ? [`${s2.turns} turn${s2.turns === 1 ? "" : "s"}`] : [];
38545
38849
  if (s2.tokens) parts.push(`${fmtTokens(s2.tokens)} tokens`);
38546
38850
  if (s2.cost) parts.push(`$${s2.cost.toFixed(3)} model cost`);
38547
- const earned = s2.impressions ? a.earn(`\u25C6 earned \u2248 $${s2.earned.toFixed(4)} from ${s2.impressions} view${s2.impressions === 1 ? "" : "s"}`) : "";
38851
+ const earned = s2.impressions ? a.earn(`\u25C6 earned \u2248 ${s2.earned.toFixed(3)} credits from ${s2.impressions} view${s2.impressions === 1 ? "" : "s"}`) : "";
38548
38852
  return ` ${a.dim(parts.join(" \xB7 "))}${earned ? ` ${earned}` : ""}
38549
38853
  `;
38550
38854
  }