modelstat 0.0.7 → 0.0.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs CHANGED
@@ -1,13 +1,42 @@
1
1
  #!/usr/bin/env node
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
9
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
10
+ }) : x)(function(x) {
11
+ if (typeof require !== "undefined") return require.apply(this, arguments);
12
+ throw Error('Dynamic require of "' + x + '" is not supported');
13
+ });
4
14
  var __esm = (fn, res) => function __init() {
5
15
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
6
16
  };
17
+ var __commonJS = (cb, mod) => function __require2() {
18
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
19
+ };
7
20
  var __export = (target, all) => {
8
21
  for (var name in all)
9
22
  __defProp(target, name, { get: all[name], enumerable: true });
10
23
  };
24
+ var __copyProps = (to, from, except, desc) => {
25
+ if (from && typeof from === "object" || typeof from === "function") {
26
+ for (let key of __getOwnPropNames(from))
27
+ if (!__hasOwnProp.call(to, key) && key !== except)
28
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
29
+ }
30
+ return to;
31
+ };
32
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
33
+ // If the importer is in node compatibility mode or this is not an ESM
34
+ // file that has been converted to a CommonJS file using a Babel-
35
+ // compatible transform (i.e. "__esModule" has not been set), then set
36
+ // "default" to the CommonJS "module.exports" for node compatibility.
37
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
38
+ mod
39
+ ));
11
40
 
12
41
  // ../../packages/parsers/src/types.ts
13
42
  var init_types = __esm({
@@ -36,7 +65,7 @@ var init_git = __esm({
36
65
  });
37
66
 
38
67
  // ../../packages/core/src/enums.ts
39
- var TOOLS, PROVIDERS, WORK_TYPES, IDENTITY_OWNER_SCOPES, INSTALL_METHODS, OS_FAMILIES, EVENT_KINDS, CLASSIFICATION_CONFIDENCE;
68
+ var TOOLS, PROVIDERS, IDENTITY_OWNER_SCOPES, INSTALL_METHODS, OS_FAMILIES, EVENT_KINDS, COMPANION_PHASES, CLASSIFICATION_CONFIDENCE;
40
69
  var init_enums = __esm({
41
70
  "../../packages/core/src/enums.ts"() {
42
71
  "use strict";
@@ -67,6 +96,12 @@ var init_enums = __esm({
67
96
  "raw_sdk_anthropic",
68
97
  "raw_sdk_openai",
69
98
  "raw_sdk_google",
99
+ // Web chat UIs (Chrome-extension companion). Categorically distinct
100
+ // from *_cli / *_desktop tools — same provider, different surface.
101
+ "chatgpt_web",
102
+ "claude_web",
103
+ "gemini_web",
104
+ "grok_web",
70
105
  "unknown"
71
106
  ];
72
107
  PROVIDERS = [
@@ -83,20 +118,6 @@ var init_enums = __esm({
83
118
  "ollama_local",
84
119
  "unknown"
85
120
  ];
86
- WORK_TYPES = [
87
- "planning",
88
- "implementation",
89
- "debugging",
90
- "review",
91
- "refactoring",
92
- "testing",
93
- "docs",
94
- "devops",
95
- "research",
96
- "ops",
97
- "chat",
98
- "misc"
99
- ];
100
121
  IDENTITY_OWNER_SCOPES = ["org", "personal", "unassigned"];
101
122
  INSTALL_METHODS = [
102
123
  "homebrew",
@@ -117,6 +138,7 @@ var init_enums = __esm({
117
138
  "snap",
118
139
  "manual",
119
140
  "docker",
141
+ "chrome_extension",
120
142
  "unknown"
121
143
  ];
122
144
  OS_FAMILIES = ["macos", "linux", "windows", "other"];
@@ -127,6 +149,17 @@ var init_enums = __esm({
127
149
  "tool_result",
128
150
  "summary"
129
151
  ];
152
+ COMPANION_PHASES = [
153
+ "starting",
154
+ "discovering",
155
+ "idle",
156
+ "scanning",
157
+ "processing",
158
+ "uploading",
159
+ "watching",
160
+ "offline",
161
+ "error"
162
+ ];
130
163
  CLASSIFICATION_CONFIDENCE = [
131
164
  "hard",
132
165
  // deterministic (from git remote, filenames, etc.)
@@ -4258,7 +4291,7 @@ var init_zod = __esm({
4258
4291
  });
4259
4292
 
4260
4293
  // ../../packages/core/src/schemas.ts
4261
- var TokenUsage, TaxonomyHint, SessionSegmentSummary, SessionSummary, GitContext, RawEvent, IngestBatch, DeviceEnrollment, DetectedInstallation, DetectedIdentity, DiscoveryReport, ClassificationConfidenceEnum;
4294
+ var TokenUsage, GitContext, RawEvent, RedactionReport, TaxonomyHintRooted, Segment, IngestBatch, HeartbeatPayload, DeviceEnrollment, DeviceSelfRegister, DeviceClaimRequest, ProcessingMetadata, RedactionPolicy, DetectedInstallation, DetectedIdentity, DiscoveryReport, ClassificationConfidenceEnum;
4262
4295
  var init_schemas = __esm({
4263
4296
  "../../packages/core/src/schemas.ts"() {
4264
4297
  "use strict";
@@ -4272,52 +4305,12 @@ var init_schemas = __esm({
4272
4305
  /** Present on reasoning-model turns (Codex gpt-5.4, Claude extended thinking). */
4273
4306
  reasoning: external_exports.number().int().nonnegative().default(0)
4274
4307
  });
4275
- TaxonomyHint = external_exports.object({
4276
- root_key: external_exports.string().max(40),
4277
- name: external_exports.string().max(120),
4278
- /** Agent's confidence, 0..1. Server may override. */
4279
- confidence: external_exports.number().min(0).max(1).default(0.7)
4280
- });
4281
- SessionSegmentSummary = external_exports.object({
4282
- /** Order within the parent session (0-based). */
4283
- idx: external_exports.number().int().nonnegative(),
4284
- started_at: external_exports.string().datetime({ offset: true }).nullable(),
4285
- ended_at: external_exports.string().datetime({ offset: true }).nullable(),
4286
- /** Per-segment tokens. Must sum to session totals (the agent should
4287
- * enforce this; the server double-checks). */
4288
- tokens: TokenUsage,
4289
- /** First/last turn index this segment covers, for debugging. */
4290
- turn_range: external_exports.tuple([external_exports.number().int(), external_exports.number().int()]).nullable().optional(),
4291
- goal: external_exports.string().max(280).nullable(),
4292
- feature: external_exports.string().max(120).nullable(),
4293
- work_type_hint: external_exports.enum(WORK_TYPES).nullable(),
4294
- domain_keywords: external_exports.array(external_exports.string().max(40)).max(16).default([]),
4295
- /** Hints this segment maps to. May span multiple roots (one segment
4296
- * can be "Projects: modelstat" + "Work types: Bug investigation"
4297
- * + "Domains: ingestion pipeline" simultaneously). */
4298
- taxonomy_hints: external_exports.array(TaxonomyHint).max(20).default([])
4299
- });
4300
- SessionSummary = external_exports.object({
4301
- goal: external_exports.string().max(280).nullable(),
4302
- feature_hint: external_exports.string().max(120).nullable(),
4303
- work_type_hint: external_exports.enum(WORK_TYPES).nullable(),
4304
- domain_keywords: external_exports.array(external_exports.string().max(40)).max(16).default([]),
4305
- /** One or more segments. If empty, the ingest endpoint will synth a
4306
- * single segment from the session's aggregate tokens. */
4307
- segments: external_exports.array(SessionSegmentSummary).max(64).default([]),
4308
- /** Counts only — the actual content never leaves the device. */
4309
- redaction_report: external_exports.object({
4310
- secrets_found: external_exports.number().int().nonnegative().default(0),
4311
- emails_redacted: external_exports.number().int().nonnegative().default(0),
4312
- paths_redacted_absolute: external_exports.number().int().nonnegative().default(0)
4313
- }).default({ secrets_found: 0, emails_redacted: 0, paths_redacted_absolute: 0 })
4314
- });
4315
4308
  GitContext = external_exports.object({
4316
4309
  remote_url: external_exports.string().nullable(),
4317
4310
  remote_host: external_exports.string().nullable(),
4318
4311
  // "github.com"
4319
4312
  remote_slug: external_exports.string().nullable(),
4320
- // "0xflair/chainvisor"
4313
+ // "org/repo"
4321
4314
  branch: external_exports.string().nullable(),
4322
4315
  commit_sha: external_exports.string().nullable()
4323
4316
  });
@@ -4348,15 +4341,49 @@ var init_schemas = __esm({
4348
4341
  source_file: external_exports.string().max(1024).nullable(),
4349
4342
  source_byte_offset: external_exports.number().int().nonnegative().nullable()
4350
4343
  });
4344
+ RedactionReport = external_exports.object({
4345
+ secrets_found: external_exports.number().int().nonnegative().default(0),
4346
+ emails_redacted: external_exports.number().int().nonnegative().default(0),
4347
+ paths_redacted_absolute: external_exports.number().int().nonnegative().default(0)
4348
+ });
4349
+ TaxonomyHintRooted = external_exports.object({
4350
+ root_key: external_exports.string().max(60),
4351
+ name: external_exports.string().max(120),
4352
+ confidence: external_exports.number().min(0).max(1).default(0.7),
4353
+ /** Optional free-text reason the companion attached this tag — surfaces
4354
+ * in the audit log so the user can see "why was this tagged X?" */
4355
+ reason: external_exports.string().max(200).optional()
4356
+ });
4357
+ Segment = external_exports.object({
4358
+ /** sha256-based deterministic id — see @modelstat/core/ids.ts segmentId(). */
4359
+ segment_id: external_exports.string().max(64),
4360
+ session_id: external_exports.string().max(120),
4361
+ tool: external_exports.enum(TOOLS),
4362
+ started_at: external_exports.string().datetime({ offset: true }),
4363
+ ended_at: external_exports.string().datetime({ offset: true }),
4364
+ /** Pre-redacted abstract, ≤ 512 chars. Never contains PII. */
4365
+ abstract: external_exports.string().max(512),
4366
+ /** Tokens spent inside this segment only. */
4367
+ tokens: TokenUsage,
4368
+ /** Tags with strongly-typed root keys. Server merges with its own
4369
+ * classifier output and files any novel names as taxonomy proposals. */
4370
+ tags: external_exports.array(TaxonomyHintRooted).max(40).default([]),
4371
+ /** Counts of what was stripped. */
4372
+ redaction: RedactionReport,
4373
+ /** `source_event_id`s covered by this segment. Used for dedupe + replay. */
4374
+ source_event_ids: external_exports.array(external_exports.string()).max(2e3),
4375
+ /** Optional embedding of the abstract (BGE-small-en-v1.5, 384 dims).
4376
+ * Present when the companion has an Embedder adapter configured.
4377
+ * Reserved for server-side similarity / clustering. */
4378
+ abstract_embedding: external_exports.array(external_exports.number()).length(384).optional()
4379
+ });
4351
4380
  IngestBatch = external_exports.object({
4352
4381
  batch_id: external_exports.string(),
4353
4382
  // ULID
4354
4383
  device_id: external_exports.string(),
4355
4384
  agent_version: external_exports.string().max(40),
4356
- schema_version: external_exports.literal(1),
4357
4385
  events: external_exports.array(RawEvent).max(1e4),
4358
- /** Optional per-session summaries, indexed by `session_id`. */
4359
- session_summaries: external_exports.record(external_exports.string(), SessionSummary).optional(),
4386
+ segments: external_exports.array(Segment).max(2e3).default([]),
4360
4387
  /** Optional per-session metadata hint: which installation produced them, etc. */
4361
4388
  session_installs: external_exports.record(
4362
4389
  external_exports.string(),
@@ -4366,6 +4393,17 @@ var init_schemas = __esm({
4366
4393
  })
4367
4394
  ).optional()
4368
4395
  });
4396
+ HeartbeatPayload = external_exports.object({
4397
+ device_id: external_exports.string(),
4398
+ status: external_exports.enum(COMPANION_PHASES),
4399
+ message: external_exports.string().max(240).nullable(),
4400
+ progress_done: external_exports.number().int().nonnegative().default(0),
4401
+ progress_total: external_exports.number().int().nonnegative().default(0),
4402
+ queue_size: external_exports.number().int().nonnegative().default(0),
4403
+ stats: external_exports.record(external_exports.string(), external_exports.unknown()).default({}),
4404
+ last_event_at: external_exports.string().datetime({ offset: true }).nullable(),
4405
+ agent_version: external_exports.string().max(40)
4406
+ });
4369
4407
  DeviceEnrollment = external_exports.object({
4370
4408
  machine_id: external_exports.string(),
4371
4409
  // stable, platform-provided
@@ -4375,6 +4413,51 @@ var init_schemas = __esm({
4375
4413
  arch: external_exports.enum(["x86_64", "arm64", "other"]),
4376
4414
  agent_version: external_exports.string().max(40)
4377
4415
  });
4416
+ DeviceSelfRegister = external_exports.object({
4417
+ /** Agent-generated UUIDv7 — must pass shape + recent-timestamp checks. */
4418
+ device_uuid: external_exports.string(),
4419
+ /** Base64-encoded ed25519 public key, exactly 32 raw bytes. Optional
4420
+ * but recommended (used for sender-constrained tokens / DPoP later). */
4421
+ public_key: external_exports.string().optional(),
4422
+ /** Free-form snapshot shown to the human on the claim page so they
4423
+ * can sanity-check what they're claiming. */
4424
+ fingerprint: external_exports.object({
4425
+ hostname: external_exports.string().max(120).optional(),
4426
+ os: external_exports.string().max(60).optional(),
4427
+ os_family: external_exports.enum(OS_FAMILIES).optional(),
4428
+ os_version: external_exports.string().max(60).optional(),
4429
+ arch: external_exports.enum(["x86_64", "arm64", "other"]).optional(),
4430
+ agent: external_exports.string().max(80).optional(),
4431
+ agent_version: external_exports.string().max(40).optional()
4432
+ // Allow extra fields for forward-compat without breaking old agents.
4433
+ }).catchall(external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean()])).default({})
4434
+ });
4435
+ DeviceClaimRequest = external_exports.object({
4436
+ claim_code: external_exports.string().max(40),
4437
+ /** Optional org_id if the user belongs to multiple orgs and wants to
4438
+ * claim into a specific one. Defaults to personal org. */
4439
+ org_id: external_exports.string().uuid().optional()
4440
+ });
4441
+ ProcessingMetadata = external_exports.object({
4442
+ redacted_by: external_exports.string().max(120).optional(),
4443
+ redaction_policy: external_exports.string().max(80).optional(),
4444
+ redaction_policy_version: external_exports.string().max(20).optional(),
4445
+ redactions_applied: external_exports.number().int().min(0).optional(),
4446
+ compacted: external_exports.boolean().optional(),
4447
+ summarized: external_exports.boolean().optional(),
4448
+ bytes_saved: external_exports.number().int().min(0).optional(),
4449
+ changes_applied: external_exports.number().int().min(0).optional(),
4450
+ original_size_bytes: external_exports.number().int().min(0).optional(),
4451
+ uploaded_size_bytes: external_exports.number().int().min(0).optional()
4452
+ });
4453
+ RedactionPolicy = external_exports.object({
4454
+ name: external_exports.string().max(60),
4455
+ version: external_exports.string().max(20),
4456
+ description: external_exports.string().max(400),
4457
+ redacts: external_exports.array(external_exports.string()).max(40),
4458
+ is_default: external_exports.boolean().default(false),
4459
+ recommended_for: external_exports.string().max(160).optional()
4460
+ });
4378
4461
  DetectedInstallation = external_exports.object({
4379
4462
  tool: external_exports.enum(TOOLS),
4380
4463
  install_method: external_exports.enum(INSTALL_METHODS),
@@ -4402,8 +4485,17 @@ var init_schemas = __esm({
4402
4485
 
4403
4486
  // ../../packages/core/src/ids.ts
4404
4487
  import { ulid } from "ulid";
4405
- function sourceEventId(deviceId, sourceFilePath, byteOffset) {
4406
- const s = `${deviceId}::${sourceFilePath}::${byteOffset}`;
4488
+ function sourceEventId(deviceId, sourceOrFilePath, byteOffsetMaybe) {
4489
+ let key;
4490
+ if (typeof sourceOrFilePath === "string") {
4491
+ const byteOffset = byteOffsetMaybe ?? 0;
4492
+ key = `fs::${sourceOrFilePath}::${byteOffset}`;
4493
+ } else if ("file" in sourceOrFilePath) {
4494
+ key = `fs::${sourceOrFilePath.file}::${sourceOrFilePath.byteOffset}`;
4495
+ } else {
4496
+ key = `web::${sourceOrFilePath.host}::${sourceOrFilePath.conversationId}::${sourceOrFilePath.messageId}`;
4497
+ }
4498
+ const s = `${deviceId}::${key}`;
4407
4499
  let h = 5381n;
4408
4500
  for (let i = 0; i < s.length; i++) {
4409
4501
  h = h * 33n ^ BigInt(s.charCodeAt(i));
@@ -4411,16 +4503,98 @@ function sourceEventId(deviceId, sourceFilePath, byteOffset) {
4411
4503
  }
4412
4504
  return `evt_${h.toString(36)}`;
4413
4505
  }
4506
+ function segmentId(sessionId, startedAtMs, endedAtMs, sourceEventIds) {
4507
+ const sorted = [...sourceEventIds].sort().join(",");
4508
+ const s = `${sessionId}|${startedAtMs}|${endedAtMs}|${sorted}`;
4509
+ let h = 5381n;
4510
+ for (let i = 0; i < s.length; i++) {
4511
+ h = h * 33n ^ BigInt(s.charCodeAt(i));
4512
+ h &= 0xffffffffffffffffn;
4513
+ }
4514
+ return `seg_${h.toString(36)}`;
4515
+ }
4516
+ var batchId;
4414
4517
  var init_ids = __esm({
4415
4518
  "../../packages/core/src/ids.ts"() {
4416
4519
  "use strict";
4520
+ batchId = () => ulid();
4417
4521
  }
4418
4522
  });
4419
4523
 
4420
4524
  // ../../packages/core/src/redact.ts
4525
+ function entropy(s) {
4526
+ const freq = /* @__PURE__ */ new Map();
4527
+ for (const c of s) freq.set(c, (freq.get(c) ?? 0) + 1);
4528
+ let h = 0;
4529
+ for (const n of freq.values()) {
4530
+ const p = n / s.length;
4531
+ h -= p * Math.log2(p);
4532
+ }
4533
+ return h;
4534
+ }
4535
+ function redact(text, repoRootAbs) {
4536
+ let out = text;
4537
+ const counts = {
4538
+ secrets_found: 0,
4539
+ emails_redacted: 0,
4540
+ paths_redacted_absolute: 0
4541
+ };
4542
+ for (const { name, pattern } of SECRET_PATTERNS) {
4543
+ out = out.replace(pattern, () => {
4544
+ counts.secrets_found += 1;
4545
+ return `[REDACTED:${name}]`;
4546
+ });
4547
+ }
4548
+ out = out.replace(TOKEN_CANDIDATE, (match) => {
4549
+ if (/^[a-f0-9]+$/i.test(match)) return match;
4550
+ if (/^[A-Z]+$/.test(match)) return match;
4551
+ const hasLetter = /[A-Za-z]/.test(match);
4552
+ const hasDigit = /\d/.test(match);
4553
+ const hasUpper = /[A-Z]/.test(match);
4554
+ const hasLower = /[a-z]/.test(match);
4555
+ if (!(hasLetter && hasDigit && hasUpper && hasLower)) return match;
4556
+ if (entropy(match) < 3.6) return match;
4557
+ counts.secrets_found += 1;
4558
+ return `[REDACTED:hi-entropy]`;
4559
+ });
4560
+ out = out.replace(EMAIL_PATTERN, () => {
4561
+ counts.emails_redacted += 1;
4562
+ return "[REDACTED:email]";
4563
+ });
4564
+ const pathReplacer = (match) => {
4565
+ if (repoRootAbs && match.startsWith(repoRootAbs)) {
4566
+ return match.slice(repoRootAbs.length).replace(/^\/+/, "./");
4567
+ }
4568
+ counts.paths_redacted_absolute += 1;
4569
+ return "[REDACTED:abs-path]";
4570
+ };
4571
+ out = out.replace(ABSOLUTE_PATH_MACOS, pathReplacer);
4572
+ out = out.replace(ABSOLUTE_PATH_LINUX, pathReplacer);
4573
+ return { text: out, counts };
4574
+ }
4575
+ var SECRET_PATTERNS, EMAIL_PATTERN, ABSOLUTE_PATH_MACOS, ABSOLUTE_PATH_LINUX, TOKEN_CANDIDATE;
4421
4576
  var init_redact = __esm({
4422
4577
  "../../packages/core/src/redact.ts"() {
4423
4578
  "use strict";
4579
+ SECRET_PATTERNS = [
4580
+ { name: "anthropic_key", pattern: /sk-ant-[A-Za-z0-9_-]{20,}/g },
4581
+ { name: "openai_key", pattern: /sk-(?:proj-)?[A-Za-z0-9_-]{20,}/g },
4582
+ { name: "google_api_key", pattern: /AIza[0-9A-Za-z_-]{35}/g },
4583
+ { name: "aws_access_key", pattern: /AKIA[0-9A-Z]{16}/g },
4584
+ { name: "aws_secret_key", pattern: /(?<![A-Za-z0-9/+=])[A-Za-z0-9/+=]{40}(?![A-Za-z0-9/+=])/g },
4585
+ { name: "github_pat", pattern: /ghp_[A-Za-z0-9]{36}/g },
4586
+ { name: "github_oauth", pattern: /gho_[A-Za-z0-9]{36}/g },
4587
+ { name: "github_app", pattern: /gh[sur]_[A-Za-z0-9]{36}/g },
4588
+ { name: "slack_token", pattern: /xox[baprs]-[A-Za-z0-9-]{10,}/g },
4589
+ { name: "stripe_live_key", pattern: /sk_live_[A-Za-z0-9]{24,}/g },
4590
+ { name: "stripe_test_key", pattern: /sk_test_[A-Za-z0-9]{24,}/g },
4591
+ { name: "jwt", pattern: /eyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g },
4592
+ { name: "private_key_header", pattern: /-----BEGIN [A-Z ]+PRIVATE KEY-----/g }
4593
+ ];
4594
+ EMAIL_PATTERN = /\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi;
4595
+ ABSOLUTE_PATH_MACOS = /\/Users\/[^\s"'`)]+/g;
4596
+ ABSOLUTE_PATH_LINUX = /\/home\/[^\s"'`)]+/g;
4597
+ TOKEN_CANDIDATE = /[A-Za-z0-9/+=_-]{32,}/g;
4424
4598
  }
4425
4599
  });
4426
4600
 
@@ -4731,140 +4905,2286 @@ var init_codex = __esm({
4731
4905
  }
4732
4906
  });
4733
4907
 
4734
- // ../../packages/parsers/src/cursor/index.ts
4735
- import Database from "better-sqlite3";
4736
- var init_cursor = __esm({
4737
- "../../packages/parsers/src/cursor/index.ts"() {
4908
+ // ../../node_modules/.pnpm/sql.js@1.14.1/node_modules/sql.js/dist/sql-wasm.js
4909
+ var require_sql_wasm = __commonJS({
4910
+ "../../node_modules/.pnpm/sql.js@1.14.1/node_modules/sql.js/dist/sql-wasm.js"(exports, module) {
4738
4911
  "use strict";
4739
- init_src();
4740
- }
4741
- });
4742
-
4743
- // ../../packages/parsers/src/discovery/index.ts
4744
- import { execFile as execFile2, execSync } from "child_process";
4745
- import { existsSync as existsSync2, statSync } from "fs";
4746
- import { homedir, platform } from "os";
4747
- import { join, resolve as resolve2 } from "path";
4748
- import { promisify as promisify2 } from "util";
4749
- async function discover(options = {}) {
4750
- const os = platform() === "darwin" ? "macos" : "linux";
4751
- const skip = new Set(options.skip ?? []);
4752
- const installations = [];
4753
- const identities = [];
4754
- for (const spec of SOURCES) {
4755
- const candidates = /* @__PURE__ */ new Set();
4756
- for (const raw of spec.dataDirs[os] ?? []) candidates.add(expandPath(raw));
4757
- for (const env of spec.dataDirEnv ?? []) {
4758
- const v = process.env[env];
4759
- if (v) candidates.add(v);
4760
- }
4761
- for (const extra of options.extraDataDirs?.[spec.tool] ?? []) candidates.add(expandPath(extra));
4762
- for (const p of candidates) {
4763
- if (existsSync2(p) && statSync(p).isDirectory()) {
4764
- installations.push({
4765
- tool: spec.tool,
4766
- install_method: "manual",
4767
- binary_path: null,
4768
- data_dir: p,
4769
- version: null,
4770
- detected_via: ["known_path"]
4912
+ var initSqlJsPromise = void 0;
4913
+ var initSqlJs2 = function(moduleConfig) {
4914
+ if (initSqlJsPromise) {
4915
+ return initSqlJsPromise;
4916
+ }
4917
+ initSqlJsPromise = new Promise(function(resolveModule, reject) {
4918
+ var Module = typeof moduleConfig !== "undefined" ? moduleConfig : {};
4919
+ var originalOnAbortFunction = Module["onAbort"];
4920
+ Module["onAbort"] = function(errorThatCausedAbort) {
4921
+ reject(new Error(errorThatCausedAbort));
4922
+ if (originalOnAbortFunction) {
4923
+ originalOnAbortFunction(errorThatCausedAbort);
4924
+ }
4925
+ };
4926
+ Module["postRun"] = Module["postRun"] || [];
4927
+ Module["postRun"].push(function() {
4928
+ resolveModule(Module);
4771
4929
  });
4772
- }
4773
- }
4774
- }
4775
- if (!skip.has("binaryWalk")) {
4776
- const binDirs = binaryLookupDirs(os);
4777
- for (const spec of SOURCES) {
4778
- for (const bin of spec.binaries ?? []) {
4779
- for (const dir of binDirs) {
4780
- const p = join(dir, bin);
4781
- if (existsSync2(p)) {
4782
- const version = await safeVersionProbe(p);
4783
- installations.push({
4784
- tool: spec.tool,
4785
- install_method: classifyInstallMethod(p, os),
4786
- binary_path: p,
4787
- data_dir: null,
4788
- version,
4789
- detected_via: ["binary_walk"]
4930
+ module = void 0;
4931
+ var k;
4932
+ k ||= typeof Module != "undefined" ? Module : {};
4933
+ var aa = !!globalThis.window, ba = !!globalThis.WorkerGlobalScope, ca = globalThis.process?.versions?.node && "renderer" != globalThis.process?.type;
4934
+ k.onRuntimeInitialized = function() {
4935
+ function a(f, l) {
4936
+ switch (typeof l) {
4937
+ case "boolean":
4938
+ bc(f, l ? 1 : 0);
4939
+ break;
4940
+ case "number":
4941
+ cc(f, l);
4942
+ break;
4943
+ case "string":
4944
+ dc(f, l, -1, -1);
4945
+ break;
4946
+ case "object":
4947
+ if (null === l) lb(f);
4948
+ else if (null != l.length) {
4949
+ var n = da(l.length);
4950
+ m.set(l, n);
4951
+ ec(f, n, l.length, -1);
4952
+ ea(n);
4953
+ } else sa(f, "Wrong API use : tried to return a value of an unknown type (" + l + ").", -1);
4954
+ break;
4955
+ default:
4956
+ lb(f);
4957
+ }
4958
+ }
4959
+ function b(f, l) {
4960
+ for (var n = [], p = 0; p < f; p += 1) {
4961
+ var u = r(l + 4 * p, "i32"), v = fc(u);
4962
+ if (1 === v || 2 === v) u = gc(u);
4963
+ else if (3 === v) u = hc(u);
4964
+ else if (4 === v) {
4965
+ v = u;
4966
+ u = ic(v);
4967
+ v = jc(v);
4968
+ for (var K = new Uint8Array(u), I = 0; I < u; I += 1) K[I] = m[v + I];
4969
+ u = K;
4970
+ } else u = null;
4971
+ n.push(u);
4972
+ }
4973
+ return n;
4974
+ }
4975
+ function c(f, l) {
4976
+ this.Qa = f;
4977
+ this.db = l;
4978
+ this.Oa = 1;
4979
+ this.mb = [];
4980
+ }
4981
+ function d(f, l) {
4982
+ this.db = l;
4983
+ this.fb = fa(f);
4984
+ if (null === this.fb) throw Error("Unable to allocate memory for the SQL string");
4985
+ this.lb = this.fb;
4986
+ this.$a = this.sb = null;
4987
+ }
4988
+ function e(f) {
4989
+ this.filename = "dbfile_" + (4294967295 * Math.random() >>> 0);
4990
+ if (null != f) {
4991
+ var l = this.filename, n = "/", p = l;
4992
+ n && (n = "string" == typeof n ? n : ha(n), p = l ? ia(n + "/" + l) : n);
4993
+ l = ja(true, true);
4994
+ p = ka(
4995
+ p,
4996
+ l
4997
+ );
4998
+ if (f) {
4999
+ if ("string" == typeof f) {
5000
+ n = Array(f.length);
5001
+ for (var u = 0, v = f.length; u < v; ++u) n[u] = f.charCodeAt(u);
5002
+ f = n;
5003
+ }
5004
+ la(p, l | 146);
5005
+ n = ma(p, 577);
5006
+ na(n, f, 0, f.length, 0);
5007
+ oa(n);
5008
+ la(p, l);
5009
+ }
5010
+ }
5011
+ this.handleError(q(this.filename, g));
5012
+ this.db = r(g, "i32");
5013
+ ob(this.db);
5014
+ this.gb = {};
5015
+ this.Sa = {};
5016
+ }
5017
+ var g = y(4), h = k.cwrap, q = h("sqlite3_open", "number", ["string", "number"]), w = h("sqlite3_close_v2", "number", ["number"]), t = h("sqlite3_exec", "number", ["number", "string", "number", "number", "number"]), x = h("sqlite3_changes", "number", ["number"]), D = h(
5018
+ "sqlite3_prepare_v2",
5019
+ "number",
5020
+ ["number", "string", "number", "number", "number"]
5021
+ ), pb = h("sqlite3_sql", "string", ["number"]), lc = h("sqlite3_normalized_sql", "string", ["number"]), qb = h("sqlite3_prepare_v2", "number", ["number", "number", "number", "number", "number"]), mc = h("sqlite3_bind_text", "number", ["number", "number", "number", "number", "number"]), rb = h("sqlite3_bind_blob", "number", ["number", "number", "number", "number", "number"]), nc = h("sqlite3_bind_double", "number", ["number", "number", "number"]), oc = h("sqlite3_bind_int", "number", [
5022
+ "number",
5023
+ "number",
5024
+ "number"
5025
+ ]), pc = h("sqlite3_bind_parameter_index", "number", ["number", "string"]), qc = h("sqlite3_step", "number", ["number"]), rc = h("sqlite3_errmsg", "string", ["number"]), sc = h("sqlite3_column_count", "number", ["number"]), tc = h("sqlite3_data_count", "number", ["number"]), uc = h("sqlite3_column_double", "number", ["number", "number"]), sb = h("sqlite3_column_text", "string", ["number", "number"]), vc = h("sqlite3_column_blob", "number", ["number", "number"]), wc = h("sqlite3_column_bytes", "number", ["number", "number"]), xc = h(
5026
+ "sqlite3_column_type",
5027
+ "number",
5028
+ ["number", "number"]
5029
+ ), yc = h("sqlite3_column_name", "string", ["number", "number"]), zc = h("sqlite3_reset", "number", ["number"]), Ac = h("sqlite3_clear_bindings", "number", ["number"]), Bc = h("sqlite3_finalize", "number", ["number"]), tb = h("sqlite3_create_function_v2", "number", "number string number number number number number number number".split(" ")), fc = h("sqlite3_value_type", "number", ["number"]), ic = h("sqlite3_value_bytes", "number", ["number"]), hc = h("sqlite3_value_text", "string", ["number"]), jc = h(
5030
+ "sqlite3_value_blob",
5031
+ "number",
5032
+ ["number"]
5033
+ ), gc = h("sqlite3_value_double", "number", ["number"]), cc = h("sqlite3_result_double", "", ["number", "number"]), lb = h("sqlite3_result_null", "", ["number"]), dc = h("sqlite3_result_text", "", ["number", "string", "number", "number"]), ec = h("sqlite3_result_blob", "", ["number", "number", "number", "number"]), bc = h("sqlite3_result_int", "", ["number", "number"]), sa = h("sqlite3_result_error", "", ["number", "string", "number"]), ub = h("sqlite3_aggregate_context", "number", ["number", "number"]), ob = h(
5034
+ "RegisterExtensionFunctions",
5035
+ "number",
5036
+ ["number"]
5037
+ ), vb = h("sqlite3_update_hook", "number", ["number", "number", "number"]);
5038
+ c.prototype.bind = function(f) {
5039
+ if (!this.Qa) throw "Statement closed";
5040
+ this.reset();
5041
+ return Array.isArray(f) ? this.Gb(f) : null != f && "object" === typeof f ? this.Hb(f) : true;
5042
+ };
5043
+ c.prototype.step = function() {
5044
+ if (!this.Qa) throw "Statement closed";
5045
+ this.Oa = 1;
5046
+ var f = qc(this.Qa);
5047
+ switch (f) {
5048
+ case 100:
5049
+ return true;
5050
+ case 101:
5051
+ return false;
5052
+ default:
5053
+ throw this.db.handleError(f);
5054
+ }
5055
+ };
5056
+ c.prototype.Ab = function(f) {
5057
+ null == f && (f = this.Oa, this.Oa += 1);
5058
+ return uc(this.Qa, f);
5059
+ };
5060
+ c.prototype.Ob = function(f) {
5061
+ null == f && (f = this.Oa, this.Oa += 1);
5062
+ f = sb(this.Qa, f);
5063
+ if ("function" !== typeof BigInt) throw Error("BigInt is not supported");
5064
+ return BigInt(f);
5065
+ };
5066
+ c.prototype.Tb = function(f) {
5067
+ null == f && (f = this.Oa, this.Oa += 1);
5068
+ return sb(this.Qa, f);
5069
+ };
5070
+ c.prototype.getBlob = function(f) {
5071
+ null == f && (f = this.Oa, this.Oa += 1);
5072
+ var l = wc(this.Qa, f);
5073
+ f = vc(this.Qa, f);
5074
+ for (var n = new Uint8Array(l), p = 0; p < l; p += 1) n[p] = m[f + p];
5075
+ return n;
5076
+ };
5077
+ c.prototype.get = function(f, l) {
5078
+ l = l || {};
5079
+ null != f && this.bind(f) && this.step();
5080
+ f = [];
5081
+ for (var n = tc(this.Qa), p = 0; p < n; p += 1) switch (xc(this.Qa, p)) {
5082
+ case 1:
5083
+ var u = l.useBigInt ? this.Ob(p) : this.Ab(p);
5084
+ f.push(u);
5085
+ break;
5086
+ case 2:
5087
+ f.push(this.Ab(p));
5088
+ break;
5089
+ case 3:
5090
+ f.push(this.Tb(p));
5091
+ break;
5092
+ case 4:
5093
+ f.push(this.getBlob(p));
5094
+ break;
5095
+ default:
5096
+ f.push(null);
5097
+ }
5098
+ return f;
5099
+ };
5100
+ c.prototype.qb = function() {
5101
+ for (var f = [], l = sc(this.Qa), n = 0; n < l; n += 1) f.push(yc(this.Qa, n));
5102
+ return f;
5103
+ };
5104
+ c.prototype.zb = function(f, l) {
5105
+ f = this.get(f, l);
5106
+ l = this.qb();
5107
+ for (var n = {}, p = 0; p < l.length; p += 1) n[l[p]] = f[p];
5108
+ return n;
5109
+ };
5110
+ c.prototype.Sb = function() {
5111
+ return pb(this.Qa);
5112
+ };
5113
+ c.prototype.Pb = function() {
5114
+ return lc(this.Qa);
5115
+ };
5116
+ c.prototype.run = function(f) {
5117
+ null != f && this.bind(f);
5118
+ this.step();
5119
+ return this.reset();
5120
+ };
5121
+ c.prototype.wb = function(f, l) {
5122
+ null == l && (l = this.Oa, this.Oa += 1);
5123
+ f = fa(f);
5124
+ this.mb.push(f);
5125
+ this.db.handleError(mc(this.Qa, l, f, -1, 0));
5126
+ };
5127
+ c.prototype.Fb = function(f, l) {
5128
+ null == l && (l = this.Oa, this.Oa += 1);
5129
+ var n = da(f.length);
5130
+ m.set(f, n);
5131
+ this.mb.push(n);
5132
+ this.db.handleError(rb(this.Qa, l, n, f.length, 0));
5133
+ };
5134
+ c.prototype.vb = function(f, l) {
5135
+ null == l && (l = this.Oa, this.Oa += 1);
5136
+ this.db.handleError((f === (f | 0) ? oc : nc)(
5137
+ this.Qa,
5138
+ l,
5139
+ f
5140
+ ));
5141
+ };
5142
+ c.prototype.Ib = function(f) {
5143
+ null == f && (f = this.Oa, this.Oa += 1);
5144
+ rb(this.Qa, f, 0, 0, 0);
5145
+ };
5146
+ c.prototype.xb = function(f, l) {
5147
+ null == l && (l = this.Oa, this.Oa += 1);
5148
+ switch (typeof f) {
5149
+ case "string":
5150
+ this.wb(f, l);
5151
+ return;
5152
+ case "number":
5153
+ this.vb(f, l);
5154
+ return;
5155
+ case "bigint":
5156
+ this.wb(f.toString(), l);
5157
+ return;
5158
+ case "boolean":
5159
+ this.vb(f + 0, l);
5160
+ return;
5161
+ case "object":
5162
+ if (null === f) {
5163
+ this.Ib(l);
5164
+ return;
5165
+ }
5166
+ if (null != f.length) {
5167
+ this.Fb(f, l);
5168
+ return;
5169
+ }
5170
+ }
5171
+ throw "Wrong API use : tried to bind a value of an unknown type (" + f + ").";
5172
+ };
5173
+ c.prototype.Hb = function(f) {
5174
+ var l = this;
5175
+ Object.keys(f).forEach(function(n) {
5176
+ var p = pc(l.Qa, n);
5177
+ 0 !== p && l.xb(f[n], p);
5178
+ });
5179
+ return true;
5180
+ };
5181
+ c.prototype.Gb = function(f) {
5182
+ for (var l = 0; l < f.length; l += 1) this.xb(f[l], l + 1);
5183
+ return true;
5184
+ };
5185
+ c.prototype.reset = function() {
5186
+ this.freemem();
5187
+ return 0 === Ac(this.Qa) && 0 === zc(this.Qa);
5188
+ };
5189
+ c.prototype.freemem = function() {
5190
+ for (var f; void 0 !== (f = this.mb.pop()); ) ea(f);
5191
+ };
5192
+ c.prototype.Ya = function() {
5193
+ this.freemem();
5194
+ var f = 0 === Bc(this.Qa);
5195
+ delete this.db.gb[this.Qa];
5196
+ this.Qa = 0;
5197
+ return f;
5198
+ };
5199
+ d.prototype.next = function() {
5200
+ if (null === this.fb) return { done: true };
5201
+ null !== this.$a && (this.$a.Ya(), this.$a = null);
5202
+ if (!this.db.db) throw this.ob(), Error("Database closed");
5203
+ var f = pa(), l = y(4);
5204
+ qa(g);
5205
+ qa(l);
5206
+ try {
5207
+ this.db.handleError(qb(this.db.db, this.lb, -1, g, l));
5208
+ this.lb = r(l, "i32");
5209
+ var n = r(g, "i32");
5210
+ if (0 === n) return this.ob(), { done: true };
5211
+ this.$a = new c(n, this.db);
5212
+ this.db.gb[n] = this.$a;
5213
+ return { value: this.$a, done: false };
5214
+ } catch (p) {
5215
+ throw this.sb = z(this.lb), this.ob(), p;
5216
+ } finally {
5217
+ ra(f);
5218
+ }
5219
+ };
5220
+ d.prototype.ob = function() {
5221
+ ea(this.fb);
5222
+ this.fb = null;
5223
+ };
5224
+ d.prototype.Qb = function() {
5225
+ return null !== this.sb ? this.sb : z(this.lb);
5226
+ };
5227
+ "function" === typeof Symbol && "symbol" === typeof Symbol.iterator && (d.prototype[Symbol.iterator] = function() {
5228
+ return this;
5229
+ });
5230
+ e.prototype.run = function(f, l) {
5231
+ if (!this.db) throw "Database closed";
5232
+ if (l) {
5233
+ f = this.tb(f, l);
5234
+ try {
5235
+ f.step();
5236
+ } finally {
5237
+ f.Ya();
5238
+ }
5239
+ } else this.handleError(t(this.db, f, 0, 0, g));
5240
+ return this;
5241
+ };
5242
+ e.prototype.exec = function(f, l, n) {
5243
+ if (!this.db) throw "Database closed";
5244
+ var p = null, u = null, v = null;
5245
+ try {
5246
+ v = u = fa(f);
5247
+ var K = y(4);
5248
+ for (f = []; 0 !== r(v, "i8"); ) {
5249
+ qa(g);
5250
+ qa(K);
5251
+ this.handleError(qb(this.db, v, -1, g, K));
5252
+ var I = r(
5253
+ g,
5254
+ "i32"
5255
+ );
5256
+ v = r(K, "i32");
5257
+ if (0 !== I) {
5258
+ var H2 = null;
5259
+ p = new c(I, this);
5260
+ for (null != l && p.bind(l); p.step(); ) null === H2 && (H2 = { columns: p.qb(), values: [] }, f.push(H2)), H2.values.push(p.get(null, n));
5261
+ p.Ya();
5262
+ }
5263
+ }
5264
+ return f;
5265
+ } catch (L) {
5266
+ throw p && p.Ya(), L;
5267
+ } finally {
5268
+ u && ea(u);
5269
+ }
5270
+ };
5271
+ e.prototype.Mb = function(f, l, n, p, u) {
5272
+ "function" === typeof l && (p = n, n = l, l = void 0);
5273
+ f = this.tb(f, l);
5274
+ try {
5275
+ for (; f.step(); ) n(f.zb(null, u));
5276
+ } finally {
5277
+ f.Ya();
5278
+ }
5279
+ if ("function" === typeof p) return p();
5280
+ };
5281
+ e.prototype.tb = function(f, l) {
5282
+ qa(g);
5283
+ this.handleError(D(this.db, f, -1, g, 0));
5284
+ f = r(g, "i32");
5285
+ if (0 === f) throw "Nothing to prepare";
5286
+ var n = new c(f, this);
5287
+ null != l && n.bind(l);
5288
+ return this.gb[f] = n;
5289
+ };
5290
+ e.prototype.Ub = function(f) {
5291
+ return new d(f, this);
5292
+ };
5293
+ e.prototype.Nb = function() {
5294
+ Object.values(this.gb).forEach(function(l) {
5295
+ l.Ya();
4790
5296
  });
5297
+ Object.values(this.Sa).forEach(A);
5298
+ this.Sa = {};
5299
+ this.handleError(w(this.db));
5300
+ var f = ta(this.filename);
5301
+ this.handleError(q(this.filename, g));
5302
+ this.db = r(g, "i32");
5303
+ ob(this.db);
5304
+ return f;
5305
+ };
5306
+ e.prototype.close = function() {
5307
+ null !== this.db && (Object.values(this.gb).forEach(function(f) {
5308
+ f.Ya();
5309
+ }), Object.values(this.Sa).forEach(A), this.Sa = {}, this.Za && (A(this.Za), this.Za = void 0), this.handleError(w(this.db)), ua("/" + this.filename), this.db = null);
5310
+ };
5311
+ e.prototype.handleError = function(f) {
5312
+ if (0 === f) return null;
5313
+ f = rc(this.db);
5314
+ throw Error(f);
5315
+ };
5316
+ e.prototype.Rb = function() {
5317
+ return x(this.db);
5318
+ };
5319
+ e.prototype.Kb = function(f, l) {
5320
+ Object.prototype.hasOwnProperty.call(this.Sa, f) && (A(this.Sa[f]), delete this.Sa[f]);
5321
+ var n = va(function(p, u, v) {
5322
+ u = b(u, v);
5323
+ try {
5324
+ var K = l.apply(null, u);
5325
+ } catch (I) {
5326
+ sa(p, I, -1);
5327
+ return;
5328
+ }
5329
+ a(p, K);
5330
+ }, "viii");
5331
+ this.Sa[f] = n;
5332
+ this.handleError(tb(
5333
+ this.db,
5334
+ f,
5335
+ l.length,
5336
+ 1,
5337
+ 0,
5338
+ n,
5339
+ 0,
5340
+ 0,
5341
+ 0
5342
+ ));
5343
+ return this;
5344
+ };
5345
+ e.prototype.Jb = function(f, l) {
5346
+ var n = l.init || function() {
5347
+ return null;
5348
+ }, p = l.finalize || function(H2) {
5349
+ return H2;
5350
+ }, u = l.step;
5351
+ if (!u) throw "An aggregate function must have a step function in " + f;
5352
+ var v = {};
5353
+ Object.hasOwnProperty.call(this.Sa, f) && (A(this.Sa[f]), delete this.Sa[f]);
5354
+ l = f + "__finalize";
5355
+ Object.hasOwnProperty.call(this.Sa, l) && (A(this.Sa[l]), delete this.Sa[l]);
5356
+ var K = va(function(H2, L, Pa) {
5357
+ var V = ub(H2, 1);
5358
+ Object.hasOwnProperty.call(v, V) || (v[V] = n());
5359
+ L = b(L, Pa);
5360
+ L = [v[V]].concat(L);
5361
+ try {
5362
+ v[V] = u.apply(null, L);
5363
+ } catch (Dc) {
5364
+ delete v[V], sa(H2, Dc, -1);
5365
+ }
5366
+ }, "viii"), I = va(function(H2) {
5367
+ var L = ub(H2, 1);
5368
+ try {
5369
+ var Pa = p(v[L]);
5370
+ } catch (V) {
5371
+ delete v[L];
5372
+ sa(H2, V, -1);
5373
+ return;
5374
+ }
5375
+ a(H2, Pa);
5376
+ delete v[L];
5377
+ }, "vi");
5378
+ this.Sa[f] = K;
5379
+ this.Sa[l] = I;
5380
+ this.handleError(tb(this.db, f, u.length - 1, 1, 0, 0, K, I, 0));
5381
+ return this;
5382
+ };
5383
+ e.prototype.Zb = function(f) {
5384
+ this.Za && (vb(this.db, 0, 0), A(this.Za), this.Za = void 0);
5385
+ if (!f) return this;
5386
+ this.Za = va(function(l, n, p, u, v) {
5387
+ switch (n) {
5388
+ case 18:
5389
+ l = "insert";
5390
+ break;
5391
+ case 23:
5392
+ l = "update";
5393
+ break;
5394
+ case 9:
5395
+ l = "delete";
5396
+ break;
5397
+ default:
5398
+ throw "unknown operationCode in updateHook callback: " + n;
5399
+ }
5400
+ p = z(p);
5401
+ u = z(u);
5402
+ if (v > Number.MAX_SAFE_INTEGER) throw "rowId too big to fit inside a Number";
5403
+ f(l, p, u, Number(v));
5404
+ }, "viiiij");
5405
+ vb(this.db, this.Za, 0);
5406
+ return this;
5407
+ };
5408
+ c.prototype.bind = c.prototype.bind;
5409
+ c.prototype.step = c.prototype.step;
5410
+ c.prototype.get = c.prototype.get;
5411
+ c.prototype.getColumnNames = c.prototype.qb;
5412
+ c.prototype.getAsObject = c.prototype.zb;
5413
+ c.prototype.getSQL = c.prototype.Sb;
5414
+ c.prototype.getNormalizedSQL = c.prototype.Pb;
5415
+ c.prototype.run = c.prototype.run;
5416
+ c.prototype.reset = c.prototype.reset;
5417
+ c.prototype.freemem = c.prototype.freemem;
5418
+ c.prototype.free = c.prototype.Ya;
5419
+ d.prototype.next = d.prototype.next;
5420
+ d.prototype.getRemainingSQL = d.prototype.Qb;
5421
+ e.prototype.run = e.prototype.run;
5422
+ e.prototype.exec = e.prototype.exec;
5423
+ e.prototype.each = e.prototype.Mb;
5424
+ e.prototype.prepare = e.prototype.tb;
5425
+ e.prototype.iterateStatements = e.prototype.Ub;
5426
+ e.prototype["export"] = e.prototype.Nb;
5427
+ e.prototype.close = e.prototype.close;
5428
+ e.prototype.handleError = e.prototype.handleError;
5429
+ e.prototype.getRowsModified = e.prototype.Rb;
5430
+ e.prototype.create_function = e.prototype.Kb;
5431
+ e.prototype.create_aggregate = e.prototype.Jb;
5432
+ e.prototype.updateHook = e.prototype.Zb;
5433
+ k.Database = e;
5434
+ };
5435
+ var wa = "./this.program", xa = (a, b) => {
5436
+ throw b;
5437
+ }, ya = globalThis.document?.currentScript?.src;
5438
+ "undefined" != typeof __filename ? ya = __filename : ba && (ya = self.location.href);
5439
+ var za = "", Aa, Ba;
5440
+ if (ca) {
5441
+ var fs2 = __require("fs");
5442
+ za = __dirname + "/";
5443
+ Ba = (a) => {
5444
+ a = Ca(a) ? new URL(a) : a;
5445
+ return fs2.readFileSync(a);
5446
+ };
5447
+ Aa = async (a) => {
5448
+ a = Ca(a) ? new URL(a) : a;
5449
+ return fs2.readFileSync(a, void 0);
5450
+ };
5451
+ 1 < process.argv.length && (wa = process.argv[1].replace(/\\/g, "/"));
5452
+ process.argv.slice(2);
5453
+ "undefined" != typeof module && (module.exports = k);
5454
+ xa = (a, b) => {
5455
+ process.exitCode = a;
5456
+ throw b;
5457
+ };
5458
+ } else if (aa || ba) {
5459
+ try {
5460
+ za = new URL(".", ya).href;
5461
+ } catch {
4791
5462
  }
4792
- }
4793
- }
4794
- }
4795
- }
4796
- if (!skip.has("appRegistry") && os === "macos") {
4797
- try {
4798
- const apps = await macosListApps();
4799
- for (const spec of SOURCES) {
4800
- for (const bid of spec.bundleIds ?? []) {
4801
- const hit = apps.find((a) => a.bundleId === bid);
4802
- if (hit) {
4803
- installations.push({
4804
- tool: spec.tool,
4805
- install_method: "app_bundle",
4806
- binary_path: hit.path,
4807
- data_dir: null,
4808
- version: hit.version,
4809
- detected_via: ["app_registry"]
5463
+ ba && (Ba = (a) => {
5464
+ var b = new XMLHttpRequest();
5465
+ b.open("GET", a, false);
5466
+ b.responseType = "arraybuffer";
5467
+ b.send(null);
5468
+ return new Uint8Array(b.response);
5469
+ });
5470
+ Aa = async (a) => {
5471
+ if (Ca(a)) return new Promise((c, d) => {
5472
+ var e = new XMLHttpRequest();
5473
+ e.open("GET", a, true);
5474
+ e.responseType = "arraybuffer";
5475
+ e.onload = () => {
5476
+ 200 == e.status || 0 == e.status && e.response ? c(e.response) : d(e.status);
5477
+ };
5478
+ e.onerror = d;
5479
+ e.send(null);
4810
5480
  });
5481
+ var b = await fetch(a, { credentials: "same-origin" });
5482
+ if (b.ok) return b.arrayBuffer();
5483
+ throw Error(b.status + " : " + b.url);
5484
+ };
5485
+ }
5486
+ var Da = console.log.bind(console), B = console.error.bind(console), Ea, Fa = false, Ga, Ca = (a) => a.startsWith("file://"), m, C, Ha, E, F, Ia, Ja, G;
5487
+ function Ka() {
5488
+ var a = La.buffer;
5489
+ m = new Int8Array(a);
5490
+ Ha = new Int16Array(a);
5491
+ C = new Uint8Array(a);
5492
+ new Uint16Array(a);
5493
+ E = new Int32Array(a);
5494
+ F = new Uint32Array(a);
5495
+ Ia = new Float32Array(a);
5496
+ Ja = new Float64Array(a);
5497
+ G = new BigInt64Array(a);
5498
+ new BigUint64Array(a);
5499
+ }
5500
+ function Ma(a) {
5501
+ k.onAbort?.(a);
5502
+ a = "Aborted(" + a + ")";
5503
+ B(a);
5504
+ Fa = true;
5505
+ throw new WebAssembly.RuntimeError(a + ". Build with -sASSERTIONS for more info.");
5506
+ }
5507
+ var Na;
5508
+ async function Oa(a) {
5509
+ if (!Ea) try {
5510
+ var b = await Aa(a);
5511
+ return new Uint8Array(b);
5512
+ } catch {
4811
5513
  }
5514
+ if (a == Na && Ea) a = new Uint8Array(Ea);
5515
+ else if (Ba) a = Ba(a);
5516
+ else throw "both async and sync fetching of the wasm failed";
5517
+ return a;
4812
5518
  }
4813
- }
4814
- } catch {
4815
- }
4816
- }
4817
- identities.push(...await probeIdentities(os));
4818
- return {
4819
- installations: dedupeInstalls(installations),
4820
- identities: dedupeIdentities(identities)
4821
- };
4822
- }
4823
- function expandPath(p) {
4824
- let s = p;
4825
- s = s.replace(/\$XDG_CONFIG_HOME/g, process.env.XDG_CONFIG_HOME ?? `${homedir()}/.config`);
4826
- s = s.replace(/\$XDG_DATA_HOME/g, process.env.XDG_DATA_HOME ?? `${homedir()}/.local/share`);
4827
- s = s.replace(/\$HOME/g, homedir());
4828
- s = H(s);
4829
- return resolve2(s);
4830
- }
4831
- function binaryLookupDirs(os) {
4832
- const dirs = /* @__PURE__ */ new Set();
4833
- (process.env.PATH ?? "").split(":").forEach((d) => d && dirs.add(d));
4834
- const extra = os === "macos" ? [
4835
- "/opt/homebrew/bin",
4836
- "/usr/local/bin",
4837
- `${homedir()}/.bun/bin`,
4838
- `${homedir()}/.volta/bin`,
4839
- `${homedir()}/.cargo/bin`,
4840
- `${homedir()}/.local/bin`,
4841
- `${homedir()}/.asdf/shims`,
4842
- `${homedir()}/.mise/shims`,
4843
- `${homedir()}/.npm-global/bin`,
4844
- `${homedir()}/.yarn/bin`
4845
- ] : [
4846
- "/usr/local/bin",
4847
- "/usr/bin",
4848
- "/snap/bin",
4849
- "/var/lib/flatpak/exports/bin",
4850
- `${homedir()}/.local/bin`,
4851
- `${homedir()}/.bun/bin`,
4852
- `${homedir()}/.cargo/bin`,
4853
- `${homedir()}/.nvm`
4854
- ];
4855
- for (const d of extra) dirs.add(d);
4856
- return Array.from(dirs);
4857
- }
4858
- function classifyInstallMethod(binPath, os) {
4859
- if (binPath.includes("/homebrew/") || binPath.includes("/Cellar/")) return "homebrew";
4860
- if (binPath.includes("/.nvm/") || binPath.includes("/node_modules/")) return "npm_global";
4861
- if (binPath.includes("/.npm-global/")) return "npm_global";
4862
- if (binPath.includes("/.pnpm/") || binPath.includes("/.pnpm-global/")) return "pnpm_global";
4863
- if (binPath.includes("/.yarn/")) return "yarn_global";
4864
- if (binPath.includes("/.bun/")) return "bun_global";
4865
- if (binPath.includes("/.cargo/")) return "cargo_install";
4866
- if (binPath.startsWith("/Applications/") || binPath.includes(".app/Contents/")) return "app_bundle";
4867
- if (os === "linux" && binPath.startsWith("/snap/")) return "snap";
5519
+ async function Qa(a, b) {
5520
+ try {
5521
+ var c = await Oa(a);
5522
+ return await WebAssembly.instantiate(c, b);
5523
+ } catch (d) {
5524
+ B(`failed to asynchronously prepare wasm: ${d}`), Ma(d);
5525
+ }
5526
+ }
5527
+ async function Ra(a) {
5528
+ var b = Na;
5529
+ if (!Ea && !Ca(b) && !ca) try {
5530
+ var c = fetch(b, { credentials: "same-origin" });
5531
+ return await WebAssembly.instantiateStreaming(c, a);
5532
+ } catch (d) {
5533
+ B(`wasm streaming compile failed: ${d}`), B("falling back to ArrayBuffer instantiation");
5534
+ }
5535
+ return Qa(b, a);
5536
+ }
5537
+ class Sa {
5538
+ name = "ExitStatus";
5539
+ constructor(a) {
5540
+ this.message = `Program terminated with exit(${a})`;
5541
+ this.status = a;
5542
+ }
5543
+ }
5544
+ var Ta = (a) => {
5545
+ for (; 0 < a.length; ) a.shift()(k);
5546
+ }, Ua = [], Va = [], Wa = () => {
5547
+ var a = k.preRun.shift();
5548
+ Va.push(a);
5549
+ }, J = 0, Xa = null;
5550
+ function r(a, b = "i8") {
5551
+ b.endsWith("*") && (b = "*");
5552
+ switch (b) {
5553
+ case "i1":
5554
+ return m[a];
5555
+ case "i8":
5556
+ return m[a];
5557
+ case "i16":
5558
+ return Ha[a >> 1];
5559
+ case "i32":
5560
+ return E[a >> 2];
5561
+ case "i64":
5562
+ return G[a >> 3];
5563
+ case "float":
5564
+ return Ia[a >> 2];
5565
+ case "double":
5566
+ return Ja[a >> 3];
5567
+ case "*":
5568
+ return F[a >> 2];
5569
+ default:
5570
+ Ma(`invalid type for getValue: ${b}`);
5571
+ }
5572
+ }
5573
+ var Ya = true;
5574
+ function qa(a) {
5575
+ var b = "i32";
5576
+ b.endsWith("*") && (b = "*");
5577
+ switch (b) {
5578
+ case "i1":
5579
+ m[a] = 0;
5580
+ break;
5581
+ case "i8":
5582
+ m[a] = 0;
5583
+ break;
5584
+ case "i16":
5585
+ Ha[a >> 1] = 0;
5586
+ break;
5587
+ case "i32":
5588
+ E[a >> 2] = 0;
5589
+ break;
5590
+ case "i64":
5591
+ G[a >> 3] = BigInt(0);
5592
+ break;
5593
+ case "float":
5594
+ Ia[a >> 2] = 0;
5595
+ break;
5596
+ case "double":
5597
+ Ja[a >> 3] = 0;
5598
+ break;
5599
+ case "*":
5600
+ F[a >> 2] = 0;
5601
+ break;
5602
+ default:
5603
+ Ma(`invalid type for setValue: ${b}`);
5604
+ }
5605
+ }
5606
+ var Za = new TextDecoder(), $a = (a, b, c, d) => {
5607
+ c = b + c;
5608
+ if (d) return c;
5609
+ for (; a[b] && !(b >= c); ) ++b;
5610
+ return b;
5611
+ }, z = (a, b, c) => a ? Za.decode(C.subarray(a, $a(C, a, b, c))) : "", ab = (a, b) => {
5612
+ for (var c = 0, d = a.length - 1; 0 <= d; d--) {
5613
+ var e = a[d];
5614
+ "." === e ? a.splice(d, 1) : ".." === e ? (a.splice(d, 1), c++) : c && (a.splice(d, 1), c--);
5615
+ }
5616
+ if (b) for (; c; c--) a.unshift("..");
5617
+ return a;
5618
+ }, ia = (a) => {
5619
+ var b = "/" === a.charAt(0), c = "/" === a.slice(-1);
5620
+ (a = ab(a.split("/").filter((d) => !!d), !b).join("/")) || b || (a = ".");
5621
+ a && c && (a += "/");
5622
+ return (b ? "/" : "") + a;
5623
+ }, bb = (a) => {
5624
+ var b = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(a).slice(1);
5625
+ a = b[0];
5626
+ b = b[1];
5627
+ if (!a && !b) return ".";
5628
+ b &&= b.slice(0, -1);
5629
+ return a + b;
5630
+ }, cb = (a) => a && a.match(/([^\/]+|\/)\/*$/)[1], db = () => {
5631
+ if (ca) {
5632
+ var a = __require("crypto");
5633
+ return (b) => a.randomFillSync(b);
5634
+ }
5635
+ return (b) => crypto.getRandomValues(b);
5636
+ }, eb = (a) => {
5637
+ (eb = db())(a);
5638
+ }, fb = (...a) => {
5639
+ for (var b = "", c = false, d = a.length - 1; -1 <= d && !c; d--) {
5640
+ c = 0 <= d ? a[d] : "/";
5641
+ if ("string" != typeof c) throw new TypeError("Arguments to path.resolve must be strings");
5642
+ if (!c) return "";
5643
+ b = c + "/" + b;
5644
+ c = "/" === c.charAt(0);
5645
+ }
5646
+ b = ab(b.split("/").filter((e) => !!e), !c).join("/");
5647
+ return (c ? "/" : "") + b || ".";
5648
+ }, gb = (a) => {
5649
+ var b = $a(a, 0);
5650
+ return Za.decode(a.buffer ? a.subarray(0, b) : new Uint8Array(a.slice(0, b)));
5651
+ }, hb = [], ib = (a) => {
5652
+ for (var b = 0, c = 0; c < a.length; ++c) {
5653
+ var d = a.charCodeAt(c);
5654
+ 127 >= d ? b++ : 2047 >= d ? b += 2 : 55296 <= d && 57343 >= d ? (b += 4, ++c) : b += 3;
5655
+ }
5656
+ return b;
5657
+ }, M = (a, b, c, d) => {
5658
+ if (!(0 < d)) return 0;
5659
+ var e = c;
5660
+ d = c + d - 1;
5661
+ for (var g = 0; g < a.length; ++g) {
5662
+ var h = a.codePointAt(g);
5663
+ if (127 >= h) {
5664
+ if (c >= d) break;
5665
+ b[c++] = h;
5666
+ } else if (2047 >= h) {
5667
+ if (c + 1 >= d) break;
5668
+ b[c++] = 192 | h >> 6;
5669
+ b[c++] = 128 | h & 63;
5670
+ } else if (65535 >= h) {
5671
+ if (c + 2 >= d) break;
5672
+ b[c++] = 224 | h >> 12;
5673
+ b[c++] = 128 | h >> 6 & 63;
5674
+ b[c++] = 128 | h & 63;
5675
+ } else {
5676
+ if (c + 3 >= d) break;
5677
+ b[c++] = 240 | h >> 18;
5678
+ b[c++] = 128 | h >> 12 & 63;
5679
+ b[c++] = 128 | h >> 6 & 63;
5680
+ b[c++] = 128 | h & 63;
5681
+ g++;
5682
+ }
5683
+ }
5684
+ b[c] = 0;
5685
+ return c - e;
5686
+ }, jb = [];
5687
+ function kb(a, b) {
5688
+ jb[a] = { input: [], output: [], eb: b };
5689
+ mb(a, nb);
5690
+ }
5691
+ var nb = { open(a) {
5692
+ var b = jb[a.node.rdev];
5693
+ if (!b) throw new N(43);
5694
+ a.tty = b;
5695
+ a.seekable = false;
5696
+ }, close(a) {
5697
+ a.tty.eb.fsync(a.tty);
5698
+ }, fsync(a) {
5699
+ a.tty.eb.fsync(a.tty);
5700
+ }, read(a, b, c, d) {
5701
+ if (!a.tty || !a.tty.eb.Bb) throw new N(60);
5702
+ for (var e = 0, g = 0; g < d; g++) {
5703
+ try {
5704
+ var h = a.tty.eb.Bb(a.tty);
5705
+ } catch (q) {
5706
+ throw new N(29);
5707
+ }
5708
+ if (void 0 === h && 0 === e) throw new N(6);
5709
+ if (null === h || void 0 === h) break;
5710
+ e++;
5711
+ b[c + g] = h;
5712
+ }
5713
+ e && (a.node.atime = Date.now());
5714
+ return e;
5715
+ }, write(a, b, c, d) {
5716
+ if (!a.tty || !a.tty.eb.ub) throw new N(60);
5717
+ try {
5718
+ for (var e = 0; e < d; e++) a.tty.eb.ub(a.tty, b[c + e]);
5719
+ } catch (g) {
5720
+ throw new N(29);
5721
+ }
5722
+ d && (a.node.mtime = a.node.ctime = Date.now());
5723
+ return e;
5724
+ } }, wb = { Bb() {
5725
+ a: {
5726
+ if (!hb.length) {
5727
+ var a = null;
5728
+ if (ca) {
5729
+ var b = Buffer.alloc(256), c = 0, d = process.stdin.fd;
5730
+ try {
5731
+ c = fs2.readSync(d, b, 0, 256);
5732
+ } catch (e) {
5733
+ if (e.toString().includes("EOF")) c = 0;
5734
+ else throw e;
5735
+ }
5736
+ 0 < c && (a = b.slice(0, c).toString("utf-8"));
5737
+ } else globalThis.window?.prompt && (a = window.prompt("Input: "), null !== a && (a += "\n"));
5738
+ if (!a) {
5739
+ a = null;
5740
+ break a;
5741
+ }
5742
+ b = Array(ib(a) + 1);
5743
+ a = M(a, b, 0, b.length);
5744
+ b.length = a;
5745
+ hb = b;
5746
+ }
5747
+ a = hb.shift();
5748
+ }
5749
+ return a;
5750
+ }, ub(a, b) {
5751
+ null === b || 10 === b ? (Da(gb(a.output)), a.output = []) : 0 != b && a.output.push(b);
5752
+ }, fsync(a) {
5753
+ 0 < a.output?.length && (Da(gb(a.output)), a.output = []);
5754
+ }, hc() {
5755
+ return { bc: 25856, dc: 5, ac: 191, cc: 35387, $b: [3, 28, 127, 21, 4, 0, 1, 0, 17, 19, 26, 0, 18, 15, 23, 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] };
5756
+ }, ic() {
5757
+ return 0;
5758
+ }, jc() {
5759
+ return [24, 80];
5760
+ } }, xb = { ub(a, b) {
5761
+ null === b || 10 === b ? (B(gb(a.output)), a.output = []) : 0 != b && a.output.push(b);
5762
+ }, fsync(a) {
5763
+ 0 < a.output?.length && (B(gb(a.output)), a.output = []);
5764
+ } }, O = { Wa: null, Xa() {
5765
+ return O.createNode(null, "/", 16895, 0);
5766
+ }, createNode(a, b, c, d) {
5767
+ if (24576 === (c & 61440) || 4096 === (c & 61440)) throw new N(63);
5768
+ O.Wa || (O.Wa = { dir: { node: { Ta: O.La.Ta, Ua: O.La.Ua, lookup: O.La.lookup, ib: O.La.ib, rename: O.La.rename, unlink: O.La.unlink, rmdir: O.La.rmdir, readdir: O.La.readdir, symlink: O.La.symlink }, stream: { Va: O.Ma.Va } }, file: { node: { Ta: O.La.Ta, Ua: O.La.Ua }, stream: { Va: O.Ma.Va, read: O.Ma.read, write: O.Ma.write, jb: O.Ma.jb, kb: O.Ma.kb } }, link: { node: { Ta: O.La.Ta, Ua: O.La.Ua, readlink: O.La.readlink }, stream: {} }, yb: { node: { Ta: O.La.Ta, Ua: O.La.Ua }, stream: yb } });
5769
+ c = zb(a, b, c, d);
5770
+ P(c.mode) ? (c.La = O.Wa.dir.node, c.Ma = O.Wa.dir.stream, c.Na = {}) : 32768 === (c.mode & 61440) ? (c.La = O.Wa.file.node, c.Ma = O.Wa.file.stream, c.Ra = 0, c.Na = null) : 40960 === (c.mode & 61440) ? (c.La = O.Wa.link.node, c.Ma = O.Wa.link.stream) : 8192 === (c.mode & 61440) && (c.La = O.Wa.yb.node, c.Ma = O.Wa.yb.stream);
5771
+ c.atime = c.mtime = c.ctime = Date.now();
5772
+ a && (a.Na[b] = c, a.atime = a.mtime = a.ctime = c.atime);
5773
+ return c;
5774
+ }, fc(a) {
5775
+ return a.Na ? a.Na.subarray ? a.Na.subarray(0, a.Ra) : new Uint8Array(a.Na) : new Uint8Array(0);
5776
+ }, La: {
5777
+ Ta(a) {
5778
+ var b = {};
5779
+ b.dev = 8192 === (a.mode & 61440) ? a.id : 1;
5780
+ b.ino = a.id;
5781
+ b.mode = a.mode;
5782
+ b.nlink = 1;
5783
+ b.uid = 0;
5784
+ b.gid = 0;
5785
+ b.rdev = a.rdev;
5786
+ P(a.mode) ? b.size = 4096 : 32768 === (a.mode & 61440) ? b.size = a.Ra : 40960 === (a.mode & 61440) ? b.size = a.link.length : b.size = 0;
5787
+ b.atime = new Date(a.atime);
5788
+ b.mtime = new Date(a.mtime);
5789
+ b.ctime = new Date(a.ctime);
5790
+ b.blksize = 4096;
5791
+ b.blocks = Math.ceil(b.size / b.blksize);
5792
+ return b;
5793
+ },
5794
+ Ua(a, b) {
5795
+ for (var c of ["mode", "atime", "mtime", "ctime"]) null != b[c] && (a[c] = b[c]);
5796
+ void 0 !== b.size && (b = b.size, a.Ra != b && (0 == b ? (a.Na = null, a.Ra = 0) : (c = a.Na, a.Na = new Uint8Array(b), c && a.Na.set(c.subarray(0, Math.min(b, a.Ra))), a.Ra = b)));
5797
+ },
5798
+ lookup() {
5799
+ O.nb || (O.nb = new N(44), O.nb.stack = "<generic error, no stack>");
5800
+ throw O.nb;
5801
+ },
5802
+ ib(a, b, c, d) {
5803
+ return O.createNode(a, b, c, d);
5804
+ },
5805
+ rename(a, b, c) {
5806
+ try {
5807
+ var d = Q(b, c);
5808
+ } catch (g) {
5809
+ }
5810
+ if (d) {
5811
+ if (P(a.mode)) for (var e in d.Na) throw new N(55);
5812
+ Ab(d);
5813
+ }
5814
+ delete a.parent.Na[a.name];
5815
+ b.Na[c] = a;
5816
+ a.name = c;
5817
+ b.ctime = b.mtime = a.parent.ctime = a.parent.mtime = Date.now();
5818
+ },
5819
+ unlink(a, b) {
5820
+ delete a.Na[b];
5821
+ a.ctime = a.mtime = Date.now();
5822
+ },
5823
+ rmdir(a, b) {
5824
+ var c = Q(a, b), d;
5825
+ for (d in c.Na) throw new N(55);
5826
+ delete a.Na[b];
5827
+ a.ctime = a.mtime = Date.now();
5828
+ },
5829
+ readdir(a) {
5830
+ return [".", "..", ...Object.keys(a.Na)];
5831
+ },
5832
+ symlink(a, b, c) {
5833
+ a = O.createNode(a, b, 41471, 0);
5834
+ a.link = c;
5835
+ return a;
5836
+ },
5837
+ readlink(a) {
5838
+ if (40960 !== (a.mode & 61440)) throw new N(28);
5839
+ return a.link;
5840
+ }
5841
+ }, Ma: { read(a, b, c, d, e) {
5842
+ var g = a.node.Na;
5843
+ if (e >= a.node.Ra) return 0;
5844
+ a = Math.min(a.node.Ra - e, d);
5845
+ if (8 < a && g.subarray) b.set(g.subarray(e, e + a), c);
5846
+ else for (d = 0; d < a; d++) b[c + d] = g[e + d];
5847
+ return a;
5848
+ }, write(a, b, c, d, e, g) {
5849
+ b.buffer === m.buffer && (g = false);
5850
+ if (!d) return 0;
5851
+ a = a.node;
5852
+ a.mtime = a.ctime = Date.now();
5853
+ if (b.subarray && (!a.Na || a.Na.subarray)) {
5854
+ if (g) return a.Na = b.subarray(c, c + d), a.Ra = d;
5855
+ if (0 === a.Ra && 0 === e) return a.Na = b.slice(c, c + d), a.Ra = d;
5856
+ if (e + d <= a.Ra) return a.Na.set(b.subarray(c, c + d), e), d;
5857
+ }
5858
+ g = e + d;
5859
+ var h = a.Na ? a.Na.length : 0;
5860
+ h >= g || (g = Math.max(g, h * (1048576 > h ? 2 : 1.125) >>> 0), 0 != h && (g = Math.max(g, 256)), h = a.Na, a.Na = new Uint8Array(g), 0 < a.Ra && a.Na.set(h.subarray(0, a.Ra), 0));
5861
+ if (a.Na.subarray && b.subarray) a.Na.set(b.subarray(c, c + d), e);
5862
+ else for (g = 0; g < d; g++) a.Na[e + g] = b[c + g];
5863
+ a.Ra = Math.max(a.Ra, e + d);
5864
+ return d;
5865
+ }, Va(a, b, c) {
5866
+ 1 === c ? b += a.position : 2 === c && 32768 === (a.node.mode & 61440) && (b += a.node.Ra);
5867
+ if (0 > b) throw new N(28);
5868
+ return b;
5869
+ }, jb(a, b, c, d, e) {
5870
+ if (32768 !== (a.node.mode & 61440)) throw new N(43);
5871
+ a = a.node.Na;
5872
+ if (e & 2 || !a || a.buffer !== m.buffer) {
5873
+ e = true;
5874
+ d = 65536 * Math.ceil(b / 65536);
5875
+ var g = Bb(65536, d);
5876
+ g && C.fill(0, g, g + d);
5877
+ d = g;
5878
+ if (!d) throw new N(48);
5879
+ if (a) {
5880
+ if (0 < c || c + b < a.length) a.subarray ? a = a.subarray(c, c + b) : a = Array.prototype.slice.call(a, c, c + b);
5881
+ m.set(a, d);
5882
+ }
5883
+ } else e = false, d = a.byteOffset;
5884
+ return { Xb: d, Eb: e };
5885
+ }, kb(a, b, c, d) {
5886
+ O.Ma.write(a, b, 0, d, c, false);
5887
+ return 0;
5888
+ } } }, ja = (a, b) => {
5889
+ var c = 0;
5890
+ a && (c |= 365);
5891
+ b && (c |= 146);
5892
+ return c;
5893
+ }, Cb = null, Db = {}, Eb = [], Fb = 1, R = null, Gb = false, Hb = true, N = class {
5894
+ name = "ErrnoError";
5895
+ constructor(a) {
5896
+ this.Pa = a;
5897
+ }
5898
+ }, Ib = class {
5899
+ hb = {};
5900
+ node = null;
5901
+ get flags() {
5902
+ return this.hb.flags;
5903
+ }
5904
+ set flags(a) {
5905
+ this.hb.flags = a;
5906
+ }
5907
+ get position() {
5908
+ return this.hb.position;
5909
+ }
5910
+ set position(a) {
5911
+ this.hb.position = a;
5912
+ }
5913
+ }, Jb = class {
5914
+ La = {};
5915
+ Ma = {};
5916
+ bb = null;
5917
+ constructor(a, b, c, d) {
5918
+ a ||= this;
5919
+ this.parent = a;
5920
+ this.Xa = a.Xa;
5921
+ this.id = Fb++;
5922
+ this.name = b;
5923
+ this.mode = c;
5924
+ this.rdev = d;
5925
+ this.atime = this.mtime = this.ctime = Date.now();
5926
+ }
5927
+ get read() {
5928
+ return 365 === (this.mode & 365);
5929
+ }
5930
+ set read(a) {
5931
+ a ? this.mode |= 365 : this.mode &= -366;
5932
+ }
5933
+ get write() {
5934
+ return 146 === (this.mode & 146);
5935
+ }
5936
+ set write(a) {
5937
+ a ? this.mode |= 146 : this.mode &= -147;
5938
+ }
5939
+ };
5940
+ function S(a, b = {}) {
5941
+ if (!a) throw new N(44);
5942
+ b.pb ?? (b.pb = true);
5943
+ "/" === a.charAt(0) || (a = "//" + a);
5944
+ var c = 0;
5945
+ a: for (; 40 > c; c++) {
5946
+ a = a.split("/").filter((q) => !!q);
5947
+ for (var d = Cb, e = "/", g = 0; g < a.length; g++) {
5948
+ var h = g === a.length - 1;
5949
+ if (h && b.parent) break;
5950
+ if ("." !== a[g]) if (".." === a[g]) if (e = bb(e), d === d.parent) {
5951
+ a = e + "/" + a.slice(g + 1).join("/");
5952
+ c--;
5953
+ continue a;
5954
+ } else d = d.parent;
5955
+ else {
5956
+ e = ia(e + "/" + a[g]);
5957
+ try {
5958
+ d = Q(d, a[g]);
5959
+ } catch (q) {
5960
+ if (44 === q?.Pa && h && b.Wb) return { path: e };
5961
+ throw q;
5962
+ }
5963
+ !d.bb || h && !b.pb || (d = d.bb.root);
5964
+ if (40960 === (d.mode & 61440) && (!h || b.ab)) {
5965
+ if (!d.La.readlink) throw new N(52);
5966
+ d = d.La.readlink(d);
5967
+ "/" === d.charAt(0) || (d = bb(e) + "/" + d);
5968
+ a = d + "/" + a.slice(g + 1).join("/");
5969
+ continue a;
5970
+ }
5971
+ }
5972
+ }
5973
+ return { path: e, node: d };
5974
+ }
5975
+ throw new N(32);
5976
+ }
5977
+ function ha(a) {
5978
+ for (var b; ; ) {
5979
+ if (a === a.parent) return a = a.Xa.Db, b ? "/" !== a[a.length - 1] ? `${a}/${b}` : a + b : a;
5980
+ b = b ? `${a.name}/${b}` : a.name;
5981
+ a = a.parent;
5982
+ }
5983
+ }
5984
+ function Kb(a, b) {
5985
+ for (var c = 0, d = 0; d < b.length; d++) c = (c << 5) - c + b.charCodeAt(d) | 0;
5986
+ return (a + c >>> 0) % R.length;
5987
+ }
5988
+ function Ab(a) {
5989
+ var b = Kb(a.parent.id, a.name);
5990
+ if (R[b] === a) R[b] = a.cb;
5991
+ else for (b = R[b]; b; ) {
5992
+ if (b.cb === a) {
5993
+ b.cb = a.cb;
5994
+ break;
5995
+ }
5996
+ b = b.cb;
5997
+ }
5998
+ }
5999
+ function Q(a, b) {
6000
+ var c = P(a.mode) ? (c = Lb(a, "x")) ? c : a.La.lookup ? 0 : 2 : 54;
6001
+ if (c) throw new N(c);
6002
+ for (c = R[Kb(a.id, b)]; c; c = c.cb) {
6003
+ var d = c.name;
6004
+ if (c.parent.id === a.id && d === b) return c;
6005
+ }
6006
+ return a.La.lookup(a, b);
6007
+ }
6008
+ function zb(a, b, c, d) {
6009
+ a = new Jb(a, b, c, d);
6010
+ b = Kb(a.parent.id, a.name);
6011
+ a.cb = R[b];
6012
+ return R[b] = a;
6013
+ }
6014
+ function P(a) {
6015
+ return 16384 === (a & 61440);
6016
+ }
6017
+ function Lb(a, b) {
6018
+ return Hb ? 0 : b.includes("r") && !(a.mode & 292) || b.includes("w") && !(a.mode & 146) || b.includes("x") && !(a.mode & 73) ? 2 : 0;
6019
+ }
6020
+ function Mb(a, b) {
6021
+ if (!P(a.mode)) return 54;
6022
+ try {
6023
+ return Q(a, b), 20;
6024
+ } catch (c) {
6025
+ }
6026
+ return Lb(a, "wx");
6027
+ }
6028
+ function Nb(a, b, c) {
6029
+ try {
6030
+ var d = Q(a, b);
6031
+ } catch (e) {
6032
+ return e.Pa;
6033
+ }
6034
+ if (a = Lb(a, "wx")) return a;
6035
+ if (c) {
6036
+ if (!P(d.mode)) return 54;
6037
+ if (d === d.parent || "/" === ha(d)) return 10;
6038
+ } else if (P(d.mode)) return 31;
6039
+ return 0;
6040
+ }
6041
+ function Ob(a) {
6042
+ if (!a) throw new N(63);
6043
+ return a;
6044
+ }
6045
+ function T(a) {
6046
+ a = Eb[a];
6047
+ if (!a) throw new N(8);
6048
+ return a;
6049
+ }
6050
+ function Pb(a, b = -1) {
6051
+ a = Object.assign(new Ib(), a);
6052
+ if (-1 == b) a: {
6053
+ for (b = 0; 4096 >= b; b++) if (!Eb[b]) break a;
6054
+ throw new N(33);
6055
+ }
6056
+ a.fd = b;
6057
+ return Eb[b] = a;
6058
+ }
6059
+ function Qb(a, b = -1) {
6060
+ a = Pb(a, b);
6061
+ a.Ma?.ec?.(a);
6062
+ return a;
6063
+ }
6064
+ function Rb(a, b, c) {
6065
+ var d = a?.Ma.Ua;
6066
+ a = d ? a : b;
6067
+ d ??= b.La.Ua;
6068
+ Ob(d);
6069
+ d(a, c);
6070
+ }
6071
+ var yb = { open(a) {
6072
+ a.Ma = Db[a.node.rdev].Ma;
6073
+ a.Ma.open?.(a);
6074
+ }, Va() {
6075
+ throw new N(70);
6076
+ } };
6077
+ function mb(a, b) {
6078
+ Db[a] = { Ma: b };
6079
+ }
6080
+ function Sb(a, b) {
6081
+ var c = "/" === b;
6082
+ if (c && Cb) throw new N(10);
6083
+ if (!c && b) {
6084
+ var d = S(b, { pb: false });
6085
+ b = d.path;
6086
+ d = d.node;
6087
+ if (d.bb) throw new N(10);
6088
+ if (!P(d.mode)) throw new N(54);
6089
+ }
6090
+ b = { type: a, kc: {}, Db: b, Vb: [] };
6091
+ a = a.Xa(b);
6092
+ a.Xa = b;
6093
+ b.root = a;
6094
+ c ? Cb = a : d && (d.bb = b, d.Xa && d.Xa.Vb.push(b));
6095
+ }
6096
+ function Tb(a, b, c) {
6097
+ var d = S(a, { parent: true }).node;
6098
+ a = cb(a);
6099
+ if (!a) throw new N(28);
6100
+ if ("." === a || ".." === a) throw new N(20);
6101
+ var e = Mb(d, a);
6102
+ if (e) throw new N(e);
6103
+ if (!d.La.ib) throw new N(63);
6104
+ return d.La.ib(d, a, b, c);
6105
+ }
6106
+ function ka(a, b = 438) {
6107
+ return Tb(a, b & 4095 | 32768, 0);
6108
+ }
6109
+ function U(a, b = 511) {
6110
+ return Tb(a, b & 1023 | 16384, 0);
6111
+ }
6112
+ function Ub(a, b, c) {
6113
+ "undefined" == typeof c && (c = b, b = 438);
6114
+ Tb(a, b | 8192, c);
6115
+ }
6116
+ function Vb(a, b) {
6117
+ if (!fb(a)) throw new N(44);
6118
+ var c = S(b, { parent: true }).node;
6119
+ if (!c) throw new N(44);
6120
+ b = cb(b);
6121
+ var d = Mb(c, b);
6122
+ if (d) throw new N(d);
6123
+ if (!c.La.symlink) throw new N(63);
6124
+ c.La.symlink(c, b, a);
6125
+ }
6126
+ function Wb(a) {
6127
+ var b = S(a, { parent: true }).node;
6128
+ a = cb(a);
6129
+ var c = Q(b, a), d = Nb(b, a, true);
6130
+ if (d) throw new N(d);
6131
+ if (!b.La.rmdir) throw new N(63);
6132
+ if (c.bb) throw new N(10);
6133
+ b.La.rmdir(b, a);
6134
+ Ab(c);
6135
+ }
6136
+ function ua(a) {
6137
+ var b = S(a, { parent: true }).node;
6138
+ if (!b) throw new N(44);
6139
+ a = cb(a);
6140
+ var c = Q(b, a), d = Nb(b, a, false);
6141
+ if (d) throw new N(d);
6142
+ if (!b.La.unlink) throw new N(63);
6143
+ if (c.bb) throw new N(10);
6144
+ b.La.unlink(b, a);
6145
+ Ab(c);
6146
+ }
6147
+ function Xb(a, b) {
6148
+ a = S(a, { ab: !b }).node;
6149
+ return Ob(a.La.Ta)(a);
6150
+ }
6151
+ function Yb(a, b, c, d) {
6152
+ Rb(a, b, { mode: c & 4095 | b.mode & -4096, ctime: Date.now(), Lb: d });
6153
+ }
6154
+ function la(a, b) {
6155
+ a = "string" == typeof a ? S(a, { ab: true }).node : a;
6156
+ Yb(null, a, b);
6157
+ }
6158
+ function Zb(a, b, c) {
6159
+ if (P(b.mode)) throw new N(31);
6160
+ if (32768 !== (b.mode & 61440)) throw new N(28);
6161
+ var d = Lb(b, "w");
6162
+ if (d) throw new N(d);
6163
+ Rb(a, b, { size: c, timestamp: Date.now() });
6164
+ }
6165
+ function ma(a, b, c = 438) {
6166
+ if ("" === a) throw new N(44);
6167
+ if ("string" == typeof b) {
6168
+ var d = { r: 0, "r+": 2, w: 577, "w+": 578, a: 1089, "a+": 1090 }[b];
6169
+ if ("undefined" == typeof d) throw Error(`Unknown file open mode: ${b}`);
6170
+ b = d;
6171
+ }
6172
+ c = b & 64 ? c & 4095 | 32768 : 0;
6173
+ if ("object" == typeof a) d = a;
6174
+ else {
6175
+ var e = a.endsWith("/");
6176
+ var g = S(a, { ab: !(b & 131072), Wb: true });
6177
+ d = g.node;
6178
+ a = g.path;
6179
+ }
6180
+ g = false;
6181
+ if (b & 64) if (d) {
6182
+ if (b & 128) throw new N(20);
6183
+ } else {
6184
+ if (e) throw new N(31);
6185
+ d = Tb(a, c | 511, 0);
6186
+ g = true;
6187
+ }
6188
+ if (!d) throw new N(44);
6189
+ 8192 === (d.mode & 61440) && (b &= -513);
6190
+ if (b & 65536 && !P(d.mode)) throw new N(54);
6191
+ if (!g && (d ? 40960 === (d.mode & 61440) ? e = 32 : (e = ["r", "w", "rw"][b & 3], b & 512 && (e += "w"), e = P(d.mode) && ("r" !== e || b & 576) ? 31 : Lb(d, e)) : e = 44, e)) throw new N(e);
6192
+ b & 512 && !g && (e = d, e = "string" == typeof e ? S(e, { ab: true }).node : e, Zb(null, e, 0));
6193
+ b = Pb({ node: d, path: ha(d), flags: b & -131713, seekable: true, position: 0, Ma: d.Ma, Yb: [], error: false });
6194
+ b.Ma.open && b.Ma.open(b);
6195
+ g && la(d, c & 511);
6196
+ return b;
6197
+ }
6198
+ function oa(a) {
6199
+ if (null === a.fd) throw new N(8);
6200
+ a.rb && (a.rb = null);
6201
+ try {
6202
+ a.Ma.close && a.Ma.close(a);
6203
+ } catch (b) {
6204
+ throw b;
6205
+ } finally {
6206
+ Eb[a.fd] = null;
6207
+ }
6208
+ a.fd = null;
6209
+ }
6210
+ function $b(a, b, c) {
6211
+ if (null === a.fd) throw new N(8);
6212
+ if (!a.seekable || !a.Ma.Va) throw new N(70);
6213
+ if (0 != c && 1 != c && 2 != c) throw new N(28);
6214
+ a.position = a.Ma.Va(a, b, c);
6215
+ a.Yb = [];
6216
+ }
6217
+ function ac(a, b, c, d, e) {
6218
+ if (0 > d || 0 > e) throw new N(28);
6219
+ if (null === a.fd) throw new N(8);
6220
+ if (1 === (a.flags & 2097155)) throw new N(8);
6221
+ if (P(a.node.mode)) throw new N(31);
6222
+ if (!a.Ma.read) throw new N(28);
6223
+ var g = "undefined" != typeof e;
6224
+ if (!g) e = a.position;
6225
+ else if (!a.seekable) throw new N(70);
6226
+ b = a.Ma.read(a, b, c, d, e);
6227
+ g || (a.position += b);
6228
+ return b;
6229
+ }
6230
+ function na(a, b, c, d, e) {
6231
+ if (0 > d || 0 > e) throw new N(28);
6232
+ if (null === a.fd) throw new N(8);
6233
+ if (0 === (a.flags & 2097155)) throw new N(8);
6234
+ if (P(a.node.mode)) throw new N(31);
6235
+ if (!a.Ma.write) throw new N(28);
6236
+ a.seekable && a.flags & 1024 && $b(a, 0, 2);
6237
+ var g = "undefined" != typeof e;
6238
+ if (!g) e = a.position;
6239
+ else if (!a.seekable) throw new N(70);
6240
+ b = a.Ma.write(a, b, c, d, e, void 0);
6241
+ g || (a.position += b);
6242
+ return b;
6243
+ }
6244
+ function ta(a) {
6245
+ var b = b || 0;
6246
+ var c = "binary";
6247
+ "utf8" !== c && "binary" !== c && Ma(`Invalid encoding type "${c}"`);
6248
+ b = ma(a, b);
6249
+ a = Xb(a).size;
6250
+ var d = new Uint8Array(a);
6251
+ ac(b, d, 0, a, 0);
6252
+ "utf8" === c && (d = gb(d));
6253
+ oa(b);
6254
+ return d;
6255
+ }
6256
+ function W(a, b, c) {
6257
+ a = ia("/dev/" + a);
6258
+ var d = ja(!!b, !!c);
6259
+ W.Cb ?? (W.Cb = 64);
6260
+ var e = W.Cb++ << 8 | 0;
6261
+ mb(e, { open(g) {
6262
+ g.seekable = false;
6263
+ }, close() {
6264
+ c?.buffer?.length && c(10);
6265
+ }, read(g, h, q, w) {
6266
+ for (var t = 0, x = 0; x < w; x++) {
6267
+ try {
6268
+ var D = b();
6269
+ } catch (pb) {
6270
+ throw new N(29);
6271
+ }
6272
+ if (void 0 === D && 0 === t) throw new N(6);
6273
+ if (null === D || void 0 === D) break;
6274
+ t++;
6275
+ h[q + x] = D;
6276
+ }
6277
+ t && (g.node.atime = Date.now());
6278
+ return t;
6279
+ }, write(g, h, q, w) {
6280
+ for (var t = 0; t < w; t++) try {
6281
+ c(h[q + t]);
6282
+ } catch (x) {
6283
+ throw new N(29);
6284
+ }
6285
+ w && (g.node.mtime = g.node.ctime = Date.now());
6286
+ return t;
6287
+ } });
6288
+ Ub(a, d, e);
6289
+ }
6290
+ var X = {};
6291
+ function Y(a, b, c) {
6292
+ if ("/" === b.charAt(0)) return b;
6293
+ a = -100 === a ? "/" : T(a).path;
6294
+ if (0 == b.length) {
6295
+ if (!c) throw new N(44);
6296
+ return a;
6297
+ }
6298
+ return a + "/" + b;
6299
+ }
6300
+ function kc(a, b) {
6301
+ F[a >> 2] = b.dev;
6302
+ F[a + 4 >> 2] = b.mode;
6303
+ F[a + 8 >> 2] = b.nlink;
6304
+ F[a + 12 >> 2] = b.uid;
6305
+ F[a + 16 >> 2] = b.gid;
6306
+ F[a + 20 >> 2] = b.rdev;
6307
+ G[a + 24 >> 3] = BigInt(b.size);
6308
+ E[a + 32 >> 2] = 4096;
6309
+ E[a + 36 >> 2] = b.blocks;
6310
+ var c = b.atime.getTime(), d = b.mtime.getTime(), e = b.ctime.getTime();
6311
+ G[a + 40 >> 3] = BigInt(Math.floor(c / 1e3));
6312
+ F[a + 48 >> 2] = c % 1e3 * 1e6;
6313
+ G[a + 56 >> 3] = BigInt(Math.floor(d / 1e3));
6314
+ F[a + 64 >> 2] = d % 1e3 * 1e6;
6315
+ G[a + 72 >> 3] = BigInt(Math.floor(e / 1e3));
6316
+ F[a + 80 >> 2] = e % 1e3 * 1e6;
6317
+ G[a + 88 >> 3] = BigInt(b.ino);
6318
+ return 0;
6319
+ }
6320
+ var Cc = void 0, Ec = () => {
6321
+ var a = E[+Cc >> 2];
6322
+ Cc += 4;
6323
+ return a;
6324
+ }, Fc = 0, Gc = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335], Hc = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334], Ic = {}, Jc = (a) => {
6325
+ Ga = a;
6326
+ Ya || 0 < Fc || (k.onExit?.(a), Fa = true);
6327
+ xa(a, new Sa(a));
6328
+ }, Kc = (a) => {
6329
+ if (!Fa) try {
6330
+ a();
6331
+ } catch (b) {
6332
+ b instanceof Sa || "unwind" == b || xa(1, b);
6333
+ } finally {
6334
+ if (!(Ya || 0 < Fc)) try {
6335
+ Ga = a = Ga, Jc(a);
6336
+ } catch (b) {
6337
+ b instanceof Sa || "unwind" == b || xa(1, b);
6338
+ }
6339
+ }
6340
+ }, Lc = {}, Nc = () => {
6341
+ if (!Mc) {
6342
+ var a = { USER: "web_user", LOGNAME: "web_user", PATH: "/", PWD: "/", HOME: "/home/web_user", LANG: (globalThis.navigator?.language ?? "C").replace("-", "_") + ".UTF-8", _: wa || "./this.program" }, b;
6343
+ for (b in Lc) void 0 === Lc[b] ? delete a[b] : a[b] = Lc[b];
6344
+ var c = [];
6345
+ for (b in a) c.push(`${b}=${a[b]}`);
6346
+ Mc = c;
6347
+ }
6348
+ return Mc;
6349
+ }, Mc, Oc = (a, b, c, d) => {
6350
+ var e = { string: (t) => {
6351
+ var x = 0;
6352
+ if (null !== t && void 0 !== t && 0 !== t) {
6353
+ x = ib(t) + 1;
6354
+ var D = y(x);
6355
+ M(t, C, D, x);
6356
+ x = D;
6357
+ }
6358
+ return x;
6359
+ }, array: (t) => {
6360
+ var x = y(t.length);
6361
+ m.set(t, x);
6362
+ return x;
6363
+ } };
6364
+ a = k["_" + a];
6365
+ var g = [], h = 0;
6366
+ if (d) for (var q = 0; q < d.length; q++) {
6367
+ var w = e[c[q]];
6368
+ w ? (0 === h && (h = pa()), g[q] = w(d[q])) : g[q] = d[q];
6369
+ }
6370
+ c = a(...g);
6371
+ return c = (function(t) {
6372
+ 0 !== h && ra(h);
6373
+ return "string" === b ? z(t) : "boolean" === b ? !!t : t;
6374
+ })(c);
6375
+ }, fa = (a) => {
6376
+ var b = ib(a) + 1, c = da(b);
6377
+ c && M(a, C, c, b);
6378
+ return c;
6379
+ }, Pc, Qc = [], A = (a) => {
6380
+ Pc.delete(Z.get(a));
6381
+ Z.set(a, null);
6382
+ Qc.push(a);
6383
+ }, Rc = (a) => {
6384
+ const b = a.length;
6385
+ return [b % 128 | 128, b >> 7, ...a];
6386
+ }, Sc = { i: 127, p: 127, j: 126, f: 125, d: 124, e: 111 }, Tc = (a) => Rc(Array.from(a, (b) => Sc[b])), va = (a, b) => {
6387
+ if (!Pc) {
6388
+ Pc = /* @__PURE__ */ new WeakMap();
6389
+ var c = Z.length;
6390
+ if (Pc) for (var d = 0; d < 0 + c; d++) {
6391
+ var e = Z.get(d);
6392
+ e && Pc.set(e, d);
6393
+ }
6394
+ }
6395
+ if (c = Pc.get(a) || 0) return c;
6396
+ c = Qc.length ? Qc.pop() : Z.grow(1);
6397
+ try {
6398
+ Z.set(c, a);
6399
+ } catch (g) {
6400
+ if (!(g instanceof TypeError)) throw g;
6401
+ b = Uint8Array.of(0, 97, 115, 109, 1, 0, 0, 0, 1, ...Rc([1, 96, ...Tc(b.slice(1)), ...Tc("v" === b[0] ? "" : b[0])]), 2, 7, 1, 1, 101, 1, 102, 0, 0, 7, 5, 1, 1, 102, 0, 0);
6402
+ b = new WebAssembly.Module(b);
6403
+ b = new WebAssembly.Instance(b, { e: { f: a } }).exports.f;
6404
+ Z.set(c, b);
6405
+ }
6406
+ Pc.set(a, c);
6407
+ return c;
6408
+ };
6409
+ R = Array(4096);
6410
+ Sb(O, "/");
6411
+ U("/tmp");
6412
+ U("/home");
6413
+ U("/home/web_user");
6414
+ (function() {
6415
+ U("/dev");
6416
+ mb(259, { read: () => 0, write: (d, e, g, h) => h, Va: () => 0 });
6417
+ Ub("/dev/null", 259);
6418
+ kb(1280, wb);
6419
+ kb(1536, xb);
6420
+ Ub("/dev/tty", 1280);
6421
+ Ub("/dev/tty1", 1536);
6422
+ var a = new Uint8Array(1024), b = 0, c = () => {
6423
+ 0 === b && (eb(a), b = a.byteLength);
6424
+ return a[--b];
6425
+ };
6426
+ W("random", c);
6427
+ W("urandom", c);
6428
+ U("/dev/shm");
6429
+ U("/dev/shm/tmp");
6430
+ })();
6431
+ (function() {
6432
+ U("/proc");
6433
+ var a = U("/proc/self");
6434
+ U("/proc/self/fd");
6435
+ Sb({ Xa() {
6436
+ var b = zb(a, "fd", 16895, 73);
6437
+ b.Ma = { Va: O.Ma.Va };
6438
+ b.La = { lookup(c, d) {
6439
+ c = +d;
6440
+ var e = T(c);
6441
+ c = { parent: null, Xa: { Db: "fake" }, La: { readlink: () => e.path }, id: c + 1 };
6442
+ return c.parent = c;
6443
+ }, readdir() {
6444
+ return Array.from(Eb.entries()).filter(([, c]) => c).map(([c]) => c.toString());
6445
+ } };
6446
+ return b;
6447
+ } }, "/proc/self/fd");
6448
+ })();
6449
+ k.noExitRuntime && (Ya = k.noExitRuntime);
6450
+ k.print && (Da = k.print);
6451
+ k.printErr && (B = k.printErr);
6452
+ k.wasmBinary && (Ea = k.wasmBinary);
6453
+ k.thisProgram && (wa = k.thisProgram);
6454
+ if (k.preInit) for ("function" == typeof k.preInit && (k.preInit = [k.preInit]); 0 < k.preInit.length; ) k.preInit.shift()();
6455
+ k.stackSave = () => pa();
6456
+ k.stackRestore = (a) => ra(a);
6457
+ k.stackAlloc = (a) => y(a);
6458
+ k.cwrap = (a, b, c, d) => {
6459
+ var e = !c || c.every((g) => "number" === g || "boolean" === g);
6460
+ return "string" !== b && e && !d ? k["_" + a] : (...g) => Oc(a, b, c, g);
6461
+ };
6462
+ k.addFunction = va;
6463
+ k.removeFunction = A;
6464
+ k.UTF8ToString = z;
6465
+ k.stringToNewUTF8 = fa;
6466
+ k.writeArrayToMemory = (a, b) => {
6467
+ m.set(a, b);
6468
+ };
6469
+ var da, ea, Bb, Uc, ra, y, pa, La, Z, Vc = {
6470
+ a: (a, b, c, d) => Ma(`Assertion failed: ${z(a)}, at: ` + [b ? z(b) : "unknown filename", c, d ? z(d) : "unknown function"]),
6471
+ i: function(a, b) {
6472
+ try {
6473
+ return a = z(a), la(a, b), 0;
6474
+ } catch (c) {
6475
+ if ("undefined" == typeof X || "ErrnoError" !== c.name) throw c;
6476
+ return -c.Pa;
6477
+ }
6478
+ },
6479
+ L: function(a, b, c) {
6480
+ try {
6481
+ b = z(b);
6482
+ b = Y(a, b);
6483
+ if (c & -8) return -28;
6484
+ var d = S(b, { ab: true }).node;
6485
+ if (!d) return -44;
6486
+ a = "";
6487
+ c & 4 && (a += "r");
6488
+ c & 2 && (a += "w");
6489
+ c & 1 && (a += "x");
6490
+ return a && Lb(d, a) ? -2 : 0;
6491
+ } catch (e) {
6492
+ if ("undefined" == typeof X || "ErrnoError" !== e.name) throw e;
6493
+ return -e.Pa;
6494
+ }
6495
+ },
6496
+ j: function(a, b) {
6497
+ try {
6498
+ var c = T(a);
6499
+ Yb(c, c.node, b, false);
6500
+ return 0;
6501
+ } catch (d) {
6502
+ if ("undefined" == typeof X || "ErrnoError" !== d.name) throw d;
6503
+ return -d.Pa;
6504
+ }
6505
+ },
6506
+ h: function(a) {
6507
+ try {
6508
+ var b = T(a);
6509
+ Rb(b, b.node, { timestamp: Date.now(), Lb: false });
6510
+ return 0;
6511
+ } catch (c) {
6512
+ if ("undefined" == typeof X || "ErrnoError" !== c.name) throw c;
6513
+ return -c.Pa;
6514
+ }
6515
+ },
6516
+ b: function(a, b, c) {
6517
+ Cc = c;
6518
+ try {
6519
+ var d = T(a);
6520
+ switch (b) {
6521
+ case 0:
6522
+ var e = Ec();
6523
+ if (0 > e) break;
6524
+ for (; Eb[e]; ) e++;
6525
+ return Qb(d, e).fd;
6526
+ case 1:
6527
+ case 2:
6528
+ return 0;
6529
+ case 3:
6530
+ return d.flags;
6531
+ case 4:
6532
+ return e = Ec(), d.flags |= e, 0;
6533
+ case 12:
6534
+ return e = Ec(), Ha[e + 0 >> 1] = 2, 0;
6535
+ case 13:
6536
+ case 14:
6537
+ return 0;
6538
+ }
6539
+ return -28;
6540
+ } catch (g) {
6541
+ if ("undefined" == typeof X || "ErrnoError" !== g.name) throw g;
6542
+ return -g.Pa;
6543
+ }
6544
+ },
6545
+ g: function(a, b) {
6546
+ try {
6547
+ var c = T(a), d = c.node, e = c.Ma.Ta;
6548
+ a = e ? c : d;
6549
+ e ??= d.La.Ta;
6550
+ Ob(e);
6551
+ var g = e(a);
6552
+ return kc(b, g);
6553
+ } catch (h) {
6554
+ if ("undefined" == typeof X || "ErrnoError" !== h.name) throw h;
6555
+ return -h.Pa;
6556
+ }
6557
+ },
6558
+ H: function(a, b) {
6559
+ b = -9007199254740992 > b || 9007199254740992 < b ? NaN : Number(b);
6560
+ try {
6561
+ if (isNaN(b)) return -61;
6562
+ var c = T(a);
6563
+ if (0 > b || 0 === (c.flags & 2097155)) throw new N(28);
6564
+ Zb(c, c.node, b);
6565
+ return 0;
6566
+ } catch (d) {
6567
+ if ("undefined" == typeof X || "ErrnoError" !== d.name) throw d;
6568
+ return -d.Pa;
6569
+ }
6570
+ },
6571
+ G: function(a, b) {
6572
+ try {
6573
+ if (0 === b) return -28;
6574
+ var c = ib("/") + 1;
6575
+ if (b < c) return -68;
6576
+ M("/", C, a, b);
6577
+ return c;
6578
+ } catch (d) {
6579
+ if ("undefined" == typeof X || "ErrnoError" !== d.name) throw d;
6580
+ return -d.Pa;
6581
+ }
6582
+ },
6583
+ K: function(a, b) {
6584
+ try {
6585
+ return a = z(a), kc(b, Xb(a, true));
6586
+ } catch (c) {
6587
+ if ("undefined" == typeof X || "ErrnoError" !== c.name) throw c;
6588
+ return -c.Pa;
6589
+ }
6590
+ },
6591
+ C: function(a, b, c) {
6592
+ try {
6593
+ return b = z(b), b = Y(a, b), U(b, c), 0;
6594
+ } catch (d) {
6595
+ if ("undefined" == typeof X || "ErrnoError" !== d.name) throw d;
6596
+ return -d.Pa;
6597
+ }
6598
+ },
6599
+ J: function(a, b, c, d) {
6600
+ try {
6601
+ b = z(b);
6602
+ var e = d & 256;
6603
+ b = Y(a, b, d & 4096);
6604
+ return kc(c, e ? Xb(b, true) : Xb(b));
6605
+ } catch (g) {
6606
+ if ("undefined" == typeof X || "ErrnoError" !== g.name) throw g;
6607
+ return -g.Pa;
6608
+ }
6609
+ },
6610
+ x: function(a, b, c, d) {
6611
+ Cc = d;
6612
+ try {
6613
+ b = z(b);
6614
+ b = Y(a, b);
6615
+ var e = d ? Ec() : 0;
6616
+ return ma(b, c, e).fd;
6617
+ } catch (g) {
6618
+ if ("undefined" == typeof X || "ErrnoError" !== g.name) throw g;
6619
+ return -g.Pa;
6620
+ }
6621
+ },
6622
+ v: function(a, b, c, d) {
6623
+ try {
6624
+ b = z(b);
6625
+ b = Y(a, b);
6626
+ if (0 >= d) return -28;
6627
+ var e = S(b).node;
6628
+ if (!e) throw new N(44);
6629
+ if (!e.La.readlink) throw new N(28);
6630
+ var g = e.La.readlink(e);
6631
+ var h = Math.min(d, ib(g)), q = m[c + h];
6632
+ M(
6633
+ g,
6634
+ C,
6635
+ c,
6636
+ d + 1
6637
+ );
6638
+ m[c + h] = q;
6639
+ return h;
6640
+ } catch (w) {
6641
+ if ("undefined" == typeof X || "ErrnoError" !== w.name) throw w;
6642
+ return -w.Pa;
6643
+ }
6644
+ },
6645
+ u: function(a) {
6646
+ try {
6647
+ return a = z(a), Wb(a), 0;
6648
+ } catch (b) {
6649
+ if ("undefined" == typeof X || "ErrnoError" !== b.name) throw b;
6650
+ return -b.Pa;
6651
+ }
6652
+ },
6653
+ f: function(a, b) {
6654
+ try {
6655
+ return a = z(a), kc(b, Xb(a));
6656
+ } catch (c) {
6657
+ if ("undefined" == typeof X || "ErrnoError" !== c.name) throw c;
6658
+ return -c.Pa;
6659
+ }
6660
+ },
6661
+ r: function(a, b, c) {
6662
+ try {
6663
+ b = z(b);
6664
+ b = Y(a, b);
6665
+ if (c) if (512 === c) Wb(b);
6666
+ else return -28;
6667
+ else ua(b);
6668
+ return 0;
6669
+ } catch (d) {
6670
+ if ("undefined" == typeof X || "ErrnoError" !== d.name) throw d;
6671
+ return -d.Pa;
6672
+ }
6673
+ },
6674
+ q: function(a, b, c) {
6675
+ try {
6676
+ b = z(b);
6677
+ b = Y(a, b, true);
6678
+ var d = Date.now(), e, g;
6679
+ if (c) {
6680
+ var h = F[c >> 2] + 4294967296 * E[c + 4 >> 2], q = E[c + 8 >> 2];
6681
+ 1073741823 == q ? e = d : 1073741822 == q ? e = null : e = 1e3 * h + q / 1e6;
6682
+ c += 16;
6683
+ h = F[c >> 2] + 4294967296 * E[c + 4 >> 2];
6684
+ q = E[c + 8 >> 2];
6685
+ 1073741823 == q ? g = d : 1073741822 == q ? g = null : g = 1e3 * h + q / 1e6;
6686
+ } else g = e = d;
6687
+ if (null !== (g ?? e)) {
6688
+ a = e;
6689
+ var w = S(b, { ab: true }).node;
6690
+ Ob(w.La.Ua)(w, { atime: a, mtime: g });
6691
+ }
6692
+ return 0;
6693
+ } catch (t) {
6694
+ if ("undefined" == typeof X || "ErrnoError" !== t.name) throw t;
6695
+ return -t.Pa;
6696
+ }
6697
+ },
6698
+ m: () => Ma(""),
6699
+ l: () => {
6700
+ Ya = false;
6701
+ Fc = 0;
6702
+ },
6703
+ A: function(a, b) {
6704
+ a = -9007199254740992 > a || 9007199254740992 < a ? NaN : Number(a);
6705
+ a = new Date(1e3 * a);
6706
+ E[b >> 2] = a.getSeconds();
6707
+ E[b + 4 >> 2] = a.getMinutes();
6708
+ E[b + 8 >> 2] = a.getHours();
6709
+ E[b + 12 >> 2] = a.getDate();
6710
+ E[b + 16 >> 2] = a.getMonth();
6711
+ E[b + 20 >> 2] = a.getFullYear() - 1900;
6712
+ E[b + 24 >> 2] = a.getDay();
6713
+ var c = a.getFullYear();
6714
+ E[b + 28 >> 2] = (0 !== c % 4 || 0 === c % 100 && 0 !== c % 400 ? Hc : Gc)[a.getMonth()] + a.getDate() - 1 | 0;
6715
+ E[b + 36 >> 2] = -(60 * a.getTimezoneOffset());
6716
+ c = new Date(a.getFullYear(), 6, 1).getTimezoneOffset();
6717
+ var d = new Date(a.getFullYear(), 0, 1).getTimezoneOffset();
6718
+ E[b + 32 >> 2] = (c != d && a.getTimezoneOffset() == Math.min(d, c)) | 0;
6719
+ },
6720
+ y: function(a, b, c, d, e, g, h) {
6721
+ e = -9007199254740992 > e || 9007199254740992 < e ? NaN : Number(e);
6722
+ try {
6723
+ var q = T(d);
6724
+ if (0 !== (b & 2) && 0 === (c & 2) && 2 !== (q.flags & 2097155)) throw new N(2);
6725
+ if (1 === (q.flags & 2097155)) throw new N(2);
6726
+ if (!q.Ma.jb) throw new N(43);
6727
+ if (!a) throw new N(28);
6728
+ var w = q.Ma.jb(q, a, e, b, c);
6729
+ var t = w.Xb;
6730
+ E[g >> 2] = w.Eb;
6731
+ F[h >> 2] = t;
6732
+ return 0;
6733
+ } catch (x) {
6734
+ if ("undefined" == typeof X || "ErrnoError" !== x.name) throw x;
6735
+ return -x.Pa;
6736
+ }
6737
+ },
6738
+ z: function(a, b, c, d, e, g) {
6739
+ g = -9007199254740992 > g || 9007199254740992 < g ? NaN : Number(g);
6740
+ try {
6741
+ var h = T(e);
6742
+ if (c & 2) {
6743
+ c = g;
6744
+ if (32768 !== (h.node.mode & 61440)) throw new N(43);
6745
+ if (!(d & 2)) {
6746
+ var q = C.slice(a, a + b);
6747
+ h.Ma.kb && h.Ma.kb(h, q, c, b, d);
6748
+ }
6749
+ }
6750
+ } catch (w) {
6751
+ if ("undefined" == typeof X || "ErrnoError" !== w.name) throw w;
6752
+ return -w.Pa;
6753
+ }
6754
+ },
6755
+ n: (a, b) => {
6756
+ Ic[a] && (clearTimeout(Ic[a].id), delete Ic[a]);
6757
+ if (!b) return 0;
6758
+ var c = setTimeout(() => {
6759
+ delete Ic[a];
6760
+ Kc(() => Uc(a, performance.now()));
6761
+ }, b);
6762
+ Ic[a] = { id: c, lc: b };
6763
+ return 0;
6764
+ },
6765
+ B: (a, b, c, d) => {
6766
+ var e = (/* @__PURE__ */ new Date()).getFullYear(), g = new Date(e, 0, 1).getTimezoneOffset();
6767
+ e = new Date(e, 6, 1).getTimezoneOffset();
6768
+ F[a >> 2] = 60 * Math.max(g, e);
6769
+ E[b >> 2] = Number(g != e);
6770
+ b = (h) => {
6771
+ var q = Math.abs(h);
6772
+ return `UTC${0 <= h ? "-" : "+"}${String(Math.floor(q / 60)).padStart(2, "0")}${String(q % 60).padStart(2, "0")}`;
6773
+ };
6774
+ a = b(g);
6775
+ b = b(e);
6776
+ e < g ? (M(a, C, c, 17), M(b, C, d, 17)) : (M(a, C, d, 17), M(b, C, c, 17));
6777
+ },
6778
+ d: () => Date.now(),
6779
+ s: () => 2147483648,
6780
+ c: () => performance.now(),
6781
+ o: (a) => {
6782
+ var b = C.length;
6783
+ a >>>= 0;
6784
+ if (2147483648 < a) return false;
6785
+ for (var c = 1; 4 >= c; c *= 2) {
6786
+ var d = b * (1 + 0.2 / c);
6787
+ d = Math.min(d, a + 100663296);
6788
+ a: {
6789
+ d = (Math.min(2147483648, 65536 * Math.ceil(Math.max(
6790
+ a,
6791
+ d
6792
+ ) / 65536)) - La.buffer.byteLength + 65535) / 65536 | 0;
6793
+ try {
6794
+ La.grow(d);
6795
+ Ka();
6796
+ var e = 1;
6797
+ break a;
6798
+ } catch (g) {
6799
+ }
6800
+ e = void 0;
6801
+ }
6802
+ if (e) return true;
6803
+ }
6804
+ return false;
6805
+ },
6806
+ E: (a, b) => {
6807
+ var c = 0, d = 0, e;
6808
+ for (e of Nc()) {
6809
+ var g = b + c;
6810
+ F[a + d >> 2] = g;
6811
+ c += M(e, C, g, Infinity) + 1;
6812
+ d += 4;
6813
+ }
6814
+ return 0;
6815
+ },
6816
+ F: (a, b) => {
6817
+ var c = Nc();
6818
+ F[a >> 2] = c.length;
6819
+ a = 0;
6820
+ for (var d of c) a += ib(d) + 1;
6821
+ F[b >> 2] = a;
6822
+ return 0;
6823
+ },
6824
+ e: function(a) {
6825
+ try {
6826
+ var b = T(a);
6827
+ oa(b);
6828
+ return 0;
6829
+ } catch (c) {
6830
+ if ("undefined" == typeof X || "ErrnoError" !== c.name) throw c;
6831
+ return c.Pa;
6832
+ }
6833
+ },
6834
+ p: function(a, b) {
6835
+ try {
6836
+ var c = T(a);
6837
+ m[b] = c.tty ? 2 : P(c.mode) ? 3 : 40960 === (c.mode & 61440) ? 7 : 4;
6838
+ Ha[b + 2 >> 1] = 0;
6839
+ G[b + 8 >> 3] = BigInt(0);
6840
+ G[b + 16 >> 3] = BigInt(0);
6841
+ return 0;
6842
+ } catch (d) {
6843
+ if ("undefined" == typeof X || "ErrnoError" !== d.name) throw d;
6844
+ return d.Pa;
6845
+ }
6846
+ },
6847
+ w: function(a, b, c, d) {
6848
+ try {
6849
+ a: {
6850
+ var e = T(a);
6851
+ a = b;
6852
+ for (var g, h = b = 0; h < c; h++) {
6853
+ var q = F[a >> 2], w = F[a + 4 >> 2];
6854
+ a += 8;
6855
+ var t = ac(e, m, q, w, g);
6856
+ if (0 > t) {
6857
+ var x = -1;
6858
+ break a;
6859
+ }
6860
+ b += t;
6861
+ if (t < w) break;
6862
+ "undefined" != typeof g && (g += t);
6863
+ }
6864
+ x = b;
6865
+ }
6866
+ F[d >> 2] = x;
6867
+ return 0;
6868
+ } catch (D) {
6869
+ if ("undefined" == typeof X || "ErrnoError" !== D.name) throw D;
6870
+ return D.Pa;
6871
+ }
6872
+ },
6873
+ D: function(a, b, c, d) {
6874
+ b = -9007199254740992 > b || 9007199254740992 < b ? NaN : Number(b);
6875
+ try {
6876
+ if (isNaN(b)) return 61;
6877
+ var e = T(a);
6878
+ $b(e, b, c);
6879
+ G[d >> 3] = BigInt(e.position);
6880
+ e.rb && 0 === b && 0 === c && (e.rb = null);
6881
+ return 0;
6882
+ } catch (g) {
6883
+ if ("undefined" == typeof X || "ErrnoError" !== g.name) throw g;
6884
+ return g.Pa;
6885
+ }
6886
+ },
6887
+ I: function(a) {
6888
+ try {
6889
+ var b = T(a);
6890
+ return b.Ma?.fsync?.(b);
6891
+ } catch (c) {
6892
+ if ("undefined" == typeof X || "ErrnoError" !== c.name) throw c;
6893
+ return c.Pa;
6894
+ }
6895
+ },
6896
+ t: function(a, b, c, d) {
6897
+ try {
6898
+ a: {
6899
+ var e = T(a);
6900
+ a = b;
6901
+ for (var g, h = b = 0; h < c; h++) {
6902
+ var q = F[a >> 2], w = F[a + 4 >> 2];
6903
+ a += 8;
6904
+ var t = na(e, m, q, w, g);
6905
+ if (0 > t) {
6906
+ var x = -1;
6907
+ break a;
6908
+ }
6909
+ b += t;
6910
+ if (t < w) break;
6911
+ "undefined" != typeof g && (g += t);
6912
+ }
6913
+ x = b;
6914
+ }
6915
+ F[d >> 2] = x;
6916
+ return 0;
6917
+ } catch (D) {
6918
+ if ("undefined" == typeof X || "ErrnoError" !== D.name) throw D;
6919
+ return D.Pa;
6920
+ }
6921
+ },
6922
+ k: Jc
6923
+ };
6924
+ function Wc() {
6925
+ function a() {
6926
+ k.calledRun = true;
6927
+ if (!Fa) {
6928
+ if (!k.noFSInit && !Gb) {
6929
+ var b, c;
6930
+ Gb = true;
6931
+ b ??= k.stdin;
6932
+ c ??= k.stdout;
6933
+ d ??= k.stderr;
6934
+ b ? W("stdin", b) : Vb("/dev/tty", "/dev/stdin");
6935
+ c ? W("stdout", null, c) : Vb("/dev/tty", "/dev/stdout");
6936
+ d ? W("stderr", null, d) : Vb("/dev/tty1", "/dev/stderr");
6937
+ ma("/dev/stdin", 0);
6938
+ ma("/dev/stdout", 1);
6939
+ ma("/dev/stderr", 1);
6940
+ }
6941
+ Xc.N();
6942
+ Hb = false;
6943
+ k.onRuntimeInitialized?.();
6944
+ if (k.postRun) for ("function" == typeof k.postRun && (k.postRun = [k.postRun]); k.postRun.length; ) {
6945
+ var d = k.postRun.shift();
6946
+ Ua.push(d);
6947
+ }
6948
+ Ta(Ua);
6949
+ }
6950
+ }
6951
+ if (0 < J) Xa = Wc;
6952
+ else {
6953
+ if (k.preRun) for ("function" == typeof k.preRun && (k.preRun = [k.preRun]); k.preRun.length; ) Wa();
6954
+ Ta(Va);
6955
+ 0 < J ? Xa = Wc : k.setStatus ? (k.setStatus("Running..."), setTimeout(() => {
6956
+ setTimeout(() => k.setStatus(""), 1);
6957
+ a();
6958
+ }, 1)) : a();
6959
+ }
6960
+ }
6961
+ var Xc;
6962
+ (async function() {
6963
+ function a(c) {
6964
+ c = Xc = c.exports;
6965
+ k._sqlite3_free = c.P;
6966
+ k._sqlite3_value_text = c.Q;
6967
+ k._sqlite3_prepare_v2 = c.R;
6968
+ k._sqlite3_step = c.S;
6969
+ k._sqlite3_reset = c.T;
6970
+ k._sqlite3_exec = c.U;
6971
+ k._sqlite3_finalize = c.V;
6972
+ k._sqlite3_column_name = c.W;
6973
+ k._sqlite3_column_text = c.X;
6974
+ k._sqlite3_column_type = c.Y;
6975
+ k._sqlite3_errmsg = c.Z;
6976
+ k._sqlite3_clear_bindings = c._;
6977
+ k._sqlite3_value_blob = c.$;
6978
+ k._sqlite3_value_bytes = c.aa;
6979
+ k._sqlite3_value_double = c.ba;
6980
+ k._sqlite3_value_int = c.ca;
6981
+ k._sqlite3_value_type = c.da;
6982
+ k._sqlite3_result_blob = c.ea;
6983
+ k._sqlite3_result_double = c.fa;
6984
+ k._sqlite3_result_error = c.ga;
6985
+ k._sqlite3_result_int = c.ha;
6986
+ k._sqlite3_result_int64 = c.ia;
6987
+ k._sqlite3_result_null = c.ja;
6988
+ k._sqlite3_result_text = c.ka;
6989
+ k._sqlite3_aggregate_context = c.la;
6990
+ k._sqlite3_column_count = c.ma;
6991
+ k._sqlite3_data_count = c.na;
6992
+ k._sqlite3_column_blob = c.oa;
6993
+ k._sqlite3_column_bytes = c.pa;
6994
+ k._sqlite3_column_double = c.qa;
6995
+ k._sqlite3_bind_blob = c.ra;
6996
+ k._sqlite3_bind_double = c.sa;
6997
+ k._sqlite3_bind_int = c.ta;
6998
+ k._sqlite3_bind_text = c.ua;
6999
+ k._sqlite3_bind_parameter_index = c.va;
7000
+ k._sqlite3_sql = c.wa;
7001
+ k._sqlite3_normalized_sql = c.xa;
7002
+ k._sqlite3_changes = c.ya;
7003
+ k._sqlite3_close_v2 = c.za;
7004
+ k._sqlite3_create_function_v2 = c.Aa;
7005
+ k._sqlite3_update_hook = c.Ba;
7006
+ k._sqlite3_open = c.Ca;
7007
+ da = k._malloc = c.Da;
7008
+ ea = k._free = c.Ea;
7009
+ k._RegisterExtensionFunctions = c.Fa;
7010
+ Bb = c.Ga;
7011
+ Uc = c.Ha;
7012
+ ra = c.Ia;
7013
+ y = c.Ja;
7014
+ pa = c.Ka;
7015
+ La = c.M;
7016
+ Z = c.O;
7017
+ Ka();
7018
+ J--;
7019
+ k.monitorRunDependencies?.(J);
7020
+ 0 == J && Xa && (c = Xa, Xa = null, c());
7021
+ return Xc;
7022
+ }
7023
+ J++;
7024
+ k.monitorRunDependencies?.(J);
7025
+ var b = { a: Vc };
7026
+ if (k.instantiateWasm) return new Promise((c) => {
7027
+ k.instantiateWasm(b, (d, e) => {
7028
+ c(a(d, e));
7029
+ });
7030
+ });
7031
+ Na ??= k.locateFile ? k.locateFile("sql-wasm.wasm", za) : za + "sql-wasm.wasm";
7032
+ return a((await Ra(b)).instance);
7033
+ })();
7034
+ Wc();
7035
+ return Module;
7036
+ });
7037
+ return initSqlJsPromise;
7038
+ };
7039
+ if (typeof exports === "object" && typeof module === "object") {
7040
+ module.exports = initSqlJs2;
7041
+ module.exports.default = initSqlJs2;
7042
+ } else if (typeof define === "function" && define["amd"]) {
7043
+ define([], function() {
7044
+ return initSqlJs2;
7045
+ });
7046
+ } else if (typeof exports === "object") {
7047
+ exports["Module"] = initSqlJs2;
7048
+ }
7049
+ }
7050
+ });
7051
+
7052
+ // ../../packages/parsers/src/cursor/index.ts
7053
+ import { readFileSync } from "fs";
7054
+ var import_sql;
7055
+ var init_cursor = __esm({
7056
+ "../../packages/parsers/src/cursor/index.ts"() {
7057
+ "use strict";
7058
+ import_sql = __toESM(require_sql_wasm(), 1);
7059
+ init_src();
7060
+ }
7061
+ });
7062
+
7063
+ // ../../packages/parsers/src/discovery/index.ts
7064
+ import { execFile as execFile2, execSync } from "child_process";
7065
+ import { existsSync as existsSync2, statSync } from "fs";
7066
+ import { homedir, platform } from "os";
7067
+ import { join, resolve as resolve2 } from "path";
7068
+ import { promisify as promisify2 } from "util";
7069
+ async function discover(options = {}) {
7070
+ const os = platform() === "darwin" ? "macos" : "linux";
7071
+ const skip = new Set(options.skip ?? []);
7072
+ const installations = [];
7073
+ const identities = [];
7074
+ for (const spec of SOURCES) {
7075
+ const candidates = /* @__PURE__ */ new Set();
7076
+ for (const raw of spec.dataDirs[os] ?? []) candidates.add(expandPath(raw));
7077
+ for (const env of spec.dataDirEnv ?? []) {
7078
+ const v = process.env[env];
7079
+ if (v) candidates.add(v);
7080
+ }
7081
+ for (const extra of options.extraDataDirs?.[spec.tool] ?? []) candidates.add(expandPath(extra));
7082
+ for (const p of candidates) {
7083
+ if (existsSync2(p) && statSync(p).isDirectory()) {
7084
+ installations.push({
7085
+ tool: spec.tool,
7086
+ install_method: "manual",
7087
+ binary_path: null,
7088
+ data_dir: p,
7089
+ version: null,
7090
+ detected_via: ["known_path"]
7091
+ });
7092
+ }
7093
+ }
7094
+ }
7095
+ if (!skip.has("binaryWalk")) {
7096
+ const binDirs = binaryLookupDirs(os);
7097
+ for (const spec of SOURCES) {
7098
+ for (const bin of spec.binaries ?? []) {
7099
+ for (const dir of binDirs) {
7100
+ const p = join(dir, bin);
7101
+ if (existsSync2(p)) {
7102
+ const version = await safeVersionProbe(p);
7103
+ installations.push({
7104
+ tool: spec.tool,
7105
+ install_method: classifyInstallMethod(p, os),
7106
+ binary_path: p,
7107
+ data_dir: null,
7108
+ version,
7109
+ detected_via: ["binary_walk"]
7110
+ });
7111
+ }
7112
+ }
7113
+ }
7114
+ }
7115
+ }
7116
+ if (!skip.has("appRegistry") && os === "macos") {
7117
+ try {
7118
+ const apps = await macosListApps();
7119
+ for (const spec of SOURCES) {
7120
+ for (const bid of spec.bundleIds ?? []) {
7121
+ const hit = apps.find((a) => a.bundleId === bid);
7122
+ if (hit) {
7123
+ installations.push({
7124
+ tool: spec.tool,
7125
+ install_method: "app_bundle",
7126
+ binary_path: hit.path,
7127
+ data_dir: null,
7128
+ version: hit.version,
7129
+ detected_via: ["app_registry"]
7130
+ });
7131
+ }
7132
+ }
7133
+ }
7134
+ } catch {
7135
+ }
7136
+ }
7137
+ identities.push(...await probeIdentities(os));
7138
+ return {
7139
+ installations: dedupeInstalls(installations),
7140
+ identities: dedupeIdentities(identities)
7141
+ };
7142
+ }
7143
+ function expandPath(p) {
7144
+ let s = p;
7145
+ s = s.replace(/\$XDG_CONFIG_HOME/g, process.env.XDG_CONFIG_HOME ?? `${homedir()}/.config`);
7146
+ s = s.replace(/\$XDG_DATA_HOME/g, process.env.XDG_DATA_HOME ?? `${homedir()}/.local/share`);
7147
+ s = s.replace(/\$HOME/g, homedir());
7148
+ s = H(s);
7149
+ return resolve2(s);
7150
+ }
7151
+ function binaryLookupDirs(os) {
7152
+ const dirs = /* @__PURE__ */ new Set();
7153
+ (process.env.PATH ?? "").split(":").forEach((d) => d && dirs.add(d));
7154
+ const extra = os === "macos" ? [
7155
+ "/opt/homebrew/bin",
7156
+ "/usr/local/bin",
7157
+ `${homedir()}/.bun/bin`,
7158
+ `${homedir()}/.volta/bin`,
7159
+ `${homedir()}/.cargo/bin`,
7160
+ `${homedir()}/.local/bin`,
7161
+ `${homedir()}/.asdf/shims`,
7162
+ `${homedir()}/.mise/shims`,
7163
+ `${homedir()}/.npm-global/bin`,
7164
+ `${homedir()}/.yarn/bin`
7165
+ ] : [
7166
+ "/usr/local/bin",
7167
+ "/usr/bin",
7168
+ "/snap/bin",
7169
+ "/var/lib/flatpak/exports/bin",
7170
+ `${homedir()}/.local/bin`,
7171
+ `${homedir()}/.bun/bin`,
7172
+ `${homedir()}/.cargo/bin`,
7173
+ `${homedir()}/.nvm`
7174
+ ];
7175
+ for (const d of extra) dirs.add(d);
7176
+ return Array.from(dirs);
7177
+ }
7178
+ function classifyInstallMethod(binPath, os) {
7179
+ if (binPath.includes("/homebrew/") || binPath.includes("/Cellar/")) return "homebrew";
7180
+ if (binPath.includes("/.nvm/") || binPath.includes("/node_modules/")) return "npm_global";
7181
+ if (binPath.includes("/.npm-global/")) return "npm_global";
7182
+ if (binPath.includes("/.pnpm/") || binPath.includes("/.pnpm-global/")) return "pnpm_global";
7183
+ if (binPath.includes("/.yarn/")) return "yarn_global";
7184
+ if (binPath.includes("/.bun/")) return "bun_global";
7185
+ if (binPath.includes("/.cargo/")) return "cargo_install";
7186
+ if (binPath.startsWith("/Applications/") || binPath.includes(".app/Contents/")) return "app_bundle";
7187
+ if (os === "linux" && binPath.startsWith("/snap/")) return "snap";
4868
7188
  if (os === "linux" && binPath.includes("/flatpak/")) return "flatpak";
4869
7189
  return "manual";
4870
7190
  }
@@ -4896,7 +7216,7 @@ async function macosListApps() {
4896
7216
  }
4897
7217
  async function probeIdentities(os) {
4898
7218
  const ids = [];
4899
- const fs = await import("fs");
7219
+ const fs2 = await import("fs");
4900
7220
  if (os === "macos") {
4901
7221
  try {
4902
7222
  const out = execSync(
@@ -4925,7 +7245,7 @@ async function probeIdentities(os) {
4925
7245
  ]) {
4926
7246
  if (!existsSync2(candidate)) continue;
4927
7247
  try {
4928
- const data = await fs.promises.readFile(candidate, "utf8");
7248
+ const data = await fs2.promises.readFile(candidate, "utf8");
4929
7249
  const obj = JSON.parse(data);
4930
7250
  const jwt = obj.tokens?.id_token;
4931
7251
  let email = null;
@@ -4965,7 +7285,7 @@ async function probeIdentities(os) {
4965
7285
  ]) {
4966
7286
  if (!existsSync2(candidate)) continue;
4967
7287
  try {
4968
- const data = await fs.promises.readFile(candidate, "utf8");
7288
+ const data = await fs2.promises.readFile(candidate, "utf8");
4969
7289
  const obj = JSON.parse(data);
4970
7290
  const email = obj.email ?? obj.token?.email;
4971
7291
  if (email) {
@@ -4986,7 +7306,7 @@ async function probeIdentities(os) {
4986
7306
  ]) {
4987
7307
  if (!existsSync2(candidate)) continue;
4988
7308
  try {
4989
- const data = await fs.promises.readFile(candidate, "utf8");
7309
+ const data = await fs2.promises.readFile(candidate, "utf8");
4990
7310
  const obj = JSON.parse(data);
4991
7311
  for (const k of Object.keys(obj)) {
4992
7312
  if (k.startsWith("cursorAuth") && typeof obj[k] === "string") {
@@ -5127,12 +7447,153 @@ var init_discovery = __esm({
5127
7447
  var init_src2 = __esm({
5128
7448
  "../../packages/parsers/src/index.ts"() {
5129
7449
  "use strict";
5130
- init_types();
5131
- init_git();
5132
- init_claude_code();
5133
- init_codex();
5134
- init_cursor();
5135
- init_discovery();
7450
+ init_types();
7451
+ init_git();
7452
+ init_claude_code();
7453
+ init_codex();
7454
+ init_cursor();
7455
+ init_discovery();
7456
+ }
7457
+ });
7458
+
7459
+ // ../../packages/companion-core/src/config/index.ts
7460
+ function expBackoff(attempt) {
7461
+ const i = Math.min(Math.max(attempt, 0), BACKOFF_MS.length - 1);
7462
+ return BACKOFF_MS[i];
7463
+ }
7464
+ var BACKOFF_MS, BACKSTOP_SCAN_MS;
7465
+ var init_config = __esm({
7466
+ "../../packages/companion-core/src/config/index.ts"() {
7467
+ "use strict";
7468
+ BACKOFF_MS = [1e3, 2500, 5e3, 1e4, 2e4, 6e4];
7469
+ BACKSTOP_SCAN_MS = 5 * 6e4;
7470
+ }
7471
+ });
7472
+
7473
+ // ../../packages/companion-core/src/http/index.ts
7474
+ function classifyStatus(status2, attempt) {
7475
+ if (status2 >= 200 && status2 < 300) return { type: "commit" };
7476
+ if (status2 === 400 || status2 === 422) return { type: "drop", reason: `http_${status2}` };
7477
+ if (status2 === 401 || status2 === 403) return { type: "reauth" };
7478
+ if (status2 === 408 || status2 === 429 || status2 >= 500) {
7479
+ return { type: "backoff", delayMs: expBackoff(attempt) };
7480
+ }
7481
+ return { type: "drop", reason: `http_${status2}` };
7482
+ }
7483
+ function sleep(ms) {
7484
+ return new Promise((r) => {
7485
+ setTimeout(r, ms);
7486
+ });
7487
+ }
7488
+ var IngestClient;
7489
+ var init_http = __esm({
7490
+ "../../packages/companion-core/src/http/index.ts"() {
7491
+ "use strict";
7492
+ init_config();
7493
+ IngestClient = class {
7494
+ constructor(opts) {
7495
+ this.opts = opts;
7496
+ this.fetchImpl = opts.fetchImpl ?? globalThis.fetch.bind(globalThis);
7497
+ this.maxAttempts = opts.maxAttempts ?? 3;
7498
+ }
7499
+ opts;
7500
+ fetchImpl;
7501
+ maxAttempts;
7502
+ async upload(batch) {
7503
+ const url = `${this.opts.apiUrl.replace(/\/+$/, "")}/v1/ingest`;
7504
+ for (let attempt = 0; attempt < this.maxAttempts; attempt++) {
7505
+ const token = await this.opts.auth.getToken();
7506
+ if (!token) {
7507
+ const reauthed = await this.opts.auth.onInvalidToken();
7508
+ if (!reauthed) return { kind: "drop", reason: "no_token" };
7509
+ continue;
7510
+ }
7511
+ let res;
7512
+ try {
7513
+ res = await this.fetchImpl(url, {
7514
+ method: "POST",
7515
+ headers: {
7516
+ "content-type": "application/json",
7517
+ authorization: `Bearer ${token}`
7518
+ },
7519
+ body: JSON.stringify(batch)
7520
+ });
7521
+ } catch (err) {
7522
+ this.opts.logger.warn("ingest fetch failed", { err: String(err), attempt });
7523
+ await sleep(expBackoff(attempt));
7524
+ continue;
7525
+ }
7526
+ const decision = classifyStatus(res.status, attempt);
7527
+ if (decision.type === "commit") {
7528
+ const body = await res.json().catch(() => ({}));
7529
+ return { kind: "commit", response: body };
7530
+ }
7531
+ if (decision.type === "drop") {
7532
+ const text = await res.text().catch(() => "");
7533
+ this.opts.logger.error("ingest dropped", {
7534
+ status: res.status,
7535
+ reason: decision.reason,
7536
+ body: text.slice(0, 500)
7537
+ });
7538
+ return { kind: "drop", reason: decision.reason };
7539
+ }
7540
+ if (decision.type === "reauth") {
7541
+ const ok = await this.opts.auth.onInvalidToken();
7542
+ if (!ok) return { kind: "drop", reason: "reauth_failed" };
7543
+ continue;
7544
+ }
7545
+ this.opts.logger.warn("ingest backoff", {
7546
+ status: res.status,
7547
+ delay_ms: decision.delayMs,
7548
+ attempt
7549
+ });
7550
+ await sleep(decision.delayMs);
7551
+ }
7552
+ return { kind: "drop", reason: "max_attempts_exceeded" };
7553
+ }
7554
+ };
7555
+ }
7556
+ });
7557
+
7558
+ // ../../packages/companion-core/src/logger.ts
7559
+ function defaultLevel() {
7560
+ const env = globalThis.process?.env ?? {};
7561
+ const raw = (env.LOG_LEVEL ?? "").toLowerCase();
7562
+ if (raw === "debug" || raw === "info" || raw === "warn" || raw === "error") return raw;
7563
+ return env.NODE_ENV === "production" ? "info" : "debug";
7564
+ }
7565
+ function consoleLogger(opts = {}) {
7566
+ const scope = opts.scope ?? "main";
7567
+ const level = opts.level ?? defaultLevel();
7568
+ const threshold = LEVEL_RANK[level];
7569
+ const emit = (lvl, msg, fields) => {
7570
+ if (LEVEL_RANK[lvl] < threshold) return;
7571
+ const prefix = `[modelstat:${scope}]`;
7572
+ const args = fields !== void 0 ? [prefix, msg, fields] : [prefix, msg];
7573
+ const fn = lvl === "warn" ? "warn" : lvl === "error" ? "error" : "log";
7574
+ console[fn](...args);
7575
+ };
7576
+ return {
7577
+ debug: (msg, fields) => emit("debug", msg, fields),
7578
+ info: (msg, fields) => emit("info", msg, fields),
7579
+ warn: (msg, fields) => emit("warn", msg, fields),
7580
+ error: (msg, fields) => emit("error", msg, fields),
7581
+ child: (childScope) => consoleLogger({ scope: `${scope}:${childScope}`, level })
7582
+ };
7583
+ }
7584
+ function createLogger(scope, opts = {}) {
7585
+ return consoleLogger({ scope, ...opts });
7586
+ }
7587
+ var LEVEL_RANK;
7588
+ var init_logger = __esm({
7589
+ "../../packages/companion-core/src/logger.ts"() {
7590
+ "use strict";
7591
+ LEVEL_RANK = {
7592
+ debug: 10,
7593
+ info: 20,
7594
+ warn: 30,
7595
+ error: 40
7596
+ };
5136
7597
  }
5137
7598
  });
5138
7599
 
@@ -5143,14 +7604,8 @@ import { existsSync as existsSync3 } from "fs";
5143
7604
  import { hostname } from "os";
5144
7605
  import { dirname as dirname2, resolve as resolve3 } from "path";
5145
7606
  import { fileURLToPath } from "url";
5146
- function machineId() {
5147
- return `dev-${hostname()}`;
5148
- }
5149
- function defaultUserEmail() {
5150
- return process.env.AGENT_USER_EMAIL ?? state.userEmail ?? "aram@dev.local";
5151
- }
5152
- var here, store, state;
5153
- var init_config = __esm({
7607
+ var here, DEFAULT_API_URL, LEGACY_LOCALHOST_API, store, state;
7608
+ var init_config2 = __esm({
5154
7609
  "src/config.ts"() {
5155
7610
  "use strict";
5156
7611
  here = dirname2(fileURLToPath(import.meta.url));
@@ -5162,20 +7617,35 @@ var init_config = __esm({
5162
7617
  }
5163
7618
  if (d === "/") break;
5164
7619
  }
7620
+ DEFAULT_API_URL = "https://modelstat.ai";
7621
+ LEGACY_LOCALHOST_API = "http://localhost:3010";
5165
7622
  store = new Conf({
5166
7623
  projectName: "modelstat-agent-dev",
5167
7624
  defaults: {
5168
- apiUrl: process.env.AGENT_API_URL ?? "http://localhost:3010",
7625
+ // Intentionally empty — the apiUrl getter below computes this
7626
+ // from env + stored value + DEFAULT_API_URL. Keeping the stored
7627
+ // default empty avoids freezing a stale value into the config
7628
+ // file the way 0.0.7 did.
7629
+ apiUrl: "",
5169
7630
  bearerToken: null,
5170
7631
  deviceId: null,
7632
+ deviceUuid: null,
7633
+ claimCode: null,
7634
+ claimUrl: null,
5171
7635
  userEmail: null,
5172
7636
  defaultOrgId: null,
5173
7637
  cursor: {}
5174
7638
  }
5175
7639
  });
5176
7640
  state = {
7641
+ /** Resolution order: env var → stored value (if user ran `setApiUrl`
7642
+ * or paired pre-0.0.8) → production default. The legacy localhost
7643
+ * value is ignored so upgrades from 0.0.7 self-heal. */
5177
7644
  get apiUrl() {
5178
- return store.get("apiUrl");
7645
+ if (process.env.AGENT_API_URL) return process.env.AGENT_API_URL;
7646
+ const stored = store.get("apiUrl");
7647
+ if (stored && stored !== LEGACY_LOCALHOST_API) return stored;
7648
+ return DEFAULT_API_URL;
5179
7649
  },
5180
7650
  setApiUrl(v) {
5181
7651
  store.set("apiUrl", v);
@@ -5198,6 +7668,24 @@ var init_config = __esm({
5198
7668
  setUserEmail(v) {
5199
7669
  store.set("userEmail", v);
5200
7670
  },
7671
+ get deviceUuid() {
7672
+ return store.get("deviceUuid");
7673
+ },
7674
+ setDeviceUuid(v) {
7675
+ store.set("deviceUuid", v);
7676
+ },
7677
+ get claimCode() {
7678
+ return store.get("claimCode");
7679
+ },
7680
+ setClaimCode(v) {
7681
+ store.set("claimCode", v);
7682
+ },
7683
+ get claimUrl() {
7684
+ return store.get("claimUrl");
7685
+ },
7686
+ setClaimUrl(v) {
7687
+ store.set("claimUrl", v);
7688
+ },
5201
7689
  getCursor(path) {
5202
7690
  return store.get("cursor")[path];
5203
7691
  },
@@ -5215,45 +7703,34 @@ var init_config = __esm({
5215
7703
 
5216
7704
  // src/api.ts
5217
7705
  import { request } from "undici";
5218
- async function startDeviceCode() {
5219
- const res = await request(`${state.apiUrl}/v1/auth/device_code`, {
7706
+ async function selfRegister(input) {
7707
+ const res = await request(`${state.apiUrl}/v1/devices/self-register`, {
5220
7708
  method: "POST",
5221
7709
  headers: { "content-type": "application/json" },
5222
- // Fastify's JSON body parser rejects an empty body when the
5223
- // content-type is application/json, so send `{}` explicitly.
5224
- body: "{}"
7710
+ body: JSON.stringify(input)
5225
7711
  });
5226
7712
  if (res.statusCode >= 300) {
5227
- throw new Error(`device_code start failed: ${res.statusCode} ${await res.body.text()}`);
7713
+ throw new Error(`self-register failed: ${res.statusCode} ${await res.body.text()}`);
5228
7714
  }
5229
7715
  return await res.body.json();
5230
7716
  }
5231
- async function pollDeviceCode(deviceCode) {
5232
- const res = await request(`${state.apiUrl}/v1/auth/device_code/poll`, {
5233
- method: "POST",
5234
- headers: { "content-type": "application/json" },
5235
- body: JSON.stringify({ device_code: deviceCode })
7717
+ async function fetchDeviceMe(secret) {
7718
+ const res = await request(`${state.apiUrl}/v1/devices/me`, {
7719
+ method: "GET",
7720
+ headers: { authorization: `Bearer ${secret}` }
5236
7721
  });
5237
- if (res.statusCode === 202) return { status: "pending" };
5238
- if (res.statusCode === 410) throw new Error("device_code expired or already claimed");
5239
7722
  if (res.statusCode >= 300) {
5240
- throw new Error(`device_code poll failed: ${res.statusCode} ${await res.body.text()}`);
7723
+ throw new Error(`devices/me failed: ${res.statusCode} ${await res.body.text()}`);
5241
7724
  }
5242
- const body = await res.body.json();
5243
- return { status: "approved", ...body };
7725
+ return await res.body.json();
5244
7726
  }
5245
- async function enrollDevice(input) {
5246
- const bearer = state.bearer;
5247
- const headers = { "content-type": "application/json" };
5248
- if (bearer) headers["authorization"] = `Bearer ${bearer}`;
5249
- const res = await request(`${state.apiUrl}/v1/devices/register`, {
7727
+ async function rotateDeviceSecret(currentSecret) {
7728
+ const res = await request(`${state.apiUrl}/v1/devices/me/rotate-secret`, {
5250
7729
  method: "POST",
5251
- headers,
5252
- body: JSON.stringify(input)
7730
+ headers: { authorization: `Bearer ${currentSecret}` }
5253
7731
  });
5254
7732
  if (res.statusCode >= 300) {
5255
- const body = await res.body.text();
5256
- throw new Error(`enrollDevice failed: ${res.statusCode} ${body}`);
7733
+ throw new Error(`rotate-secret failed: ${res.statusCode} ${await res.body.text()}`);
5257
7734
  }
5258
7735
  return await res.body.json();
5259
7736
  }
@@ -5270,118 +7747,436 @@ async function reportDiscovery(report) {
5270
7747
  throw new Error(`reportDiscovery failed: ${res.statusCode} ${body}`);
5271
7748
  }
5272
7749
  }
5273
- async function uploadBatch(batch) {
5274
- const bearer = state.bearer;
5275
- if (!bearer) throw new Error("agent not enrolled");
5276
- const res = await request(`${state.apiUrl}/v1/ingest`, {
5277
- method: "POST",
5278
- headers: { "content-type": "application/json", authorization: `Bearer ${bearer}` },
5279
- body: JSON.stringify(batch)
7750
+ async function fetchDeviceViewByClaim(claimCode) {
7751
+ const res = await request(`${state.apiUrl}/v1/d/${encodeURIComponent(claimCode)}`, {
7752
+ method: "GET"
5280
7753
  });
5281
- const body = await res.body.text();
7754
+ if (res.statusCode === 404) return null;
7755
+ if (res.statusCode >= 300) {
7756
+ throw new Error(`device-view failed: ${res.statusCode} ${await res.body.text()}`);
7757
+ }
7758
+ return await res.body.json();
7759
+ }
7760
+ async function fetchDeviceViewJobsByClaim(claimCode) {
7761
+ const res = await request(
7762
+ `${state.apiUrl}/v1/d/${encodeURIComponent(claimCode)}/jobs`,
7763
+ { method: "GET" }
7764
+ );
7765
+ if (res.statusCode === 404) return null;
7766
+ if (res.statusCode >= 300) {
7767
+ throw new Error(`device-view jobs failed: ${res.statusCode} ${await res.body.text()}`);
7768
+ }
7769
+ return await res.body.json();
7770
+ }
7771
+ async function fetchDeviceViewLedgerByClaim(claimCode) {
7772
+ const res = await request(
7773
+ `${state.apiUrl}/v1/d/${encodeURIComponent(claimCode)}/ledger`,
7774
+ { method: "GET" }
7775
+ );
7776
+ if (res.statusCode === 404) return null;
5282
7777
  if (res.statusCode >= 300) {
5283
- throw new Error(`upload failed: ${res.statusCode} ${body}`);
7778
+ throw new Error(`device-view ledger failed: ${res.statusCode} ${await res.body.text()}`);
7779
+ }
7780
+ return await res.body.json();
7781
+ }
7782
+ function ingestClient() {
7783
+ if (_ingest) return _ingest;
7784
+ const logger = createLogger("agent.ingest");
7785
+ _ingest = new IngestClient({
7786
+ apiUrl: state.apiUrl,
7787
+ auth: {
7788
+ getToken: async () => state.bearer,
7789
+ onInvalidToken: async () => {
7790
+ const current = state.bearer;
7791
+ if (!current) return false;
7792
+ try {
7793
+ await rotateDeviceSecret(current);
7794
+ return !!state.bearer;
7795
+ } catch {
7796
+ return false;
7797
+ }
7798
+ }
7799
+ },
7800
+ logger
7801
+ });
7802
+ return _ingest;
7803
+ }
7804
+ async function uploadBatch(batch) {
7805
+ const result = await ingestClient().upload(batch);
7806
+ if (result.kind !== "commit") {
7807
+ throw new Error(`upload failed: ${result.reason}`);
5284
7808
  }
5285
- return JSON.parse(body);
7809
+ return {
7810
+ accepted: result.response.accepted,
7811
+ new_sessions: result.response.new_sessions,
7812
+ updated_sessions: result.response.updated_sessions,
7813
+ batch_id: result.response.batch_id
7814
+ };
5286
7815
  }
7816
+ var _ingest;
5287
7817
  var init_api = __esm({
5288
7818
  "src/api.ts"() {
7819
+ "use strict";
7820
+ init_http();
7821
+ init_logger();
7822
+ init_config2();
7823
+ _ingest = null;
7824
+ }
7825
+ });
7826
+
7827
+ // ../../packages/companion-core/src/contracts/index.ts
7828
+ var init_contracts = __esm({
7829
+ "../../packages/companion-core/src/contracts/index.ts"() {
7830
+ "use strict";
7831
+ init_schemas();
7832
+ init_enums();
7833
+ }
7834
+ });
7835
+
7836
+ // ../../packages/companion-core/src/ids.ts
7837
+ var init_ids2 = __esm({
7838
+ "../../packages/companion-core/src/ids.ts"() {
7839
+ "use strict";
7840
+ init_ids();
7841
+ }
7842
+ });
7843
+
7844
+ // ../../packages/companion-core/src/queue/index.ts
7845
+ var init_queue = __esm({
7846
+ "../../packages/companion-core/src/queue/index.ts"() {
5289
7847
  "use strict";
5290
7848
  init_config();
7849
+ init_ids2();
7850
+ }
7851
+ });
7852
+
7853
+ // ../../packages/companion-core/src/pipeline/prompts.ts
7854
+ var OLLAMA_CHAT_MODEL, OLLAMA_EMBED_MODEL, SUMMARISER_SYSTEM_PROMPT, SUMMARISER_MAX_TOKENS, SUMMARISER_TEMPERATURE, QWEN_CHARS_PER_TOKEN;
7855
+ var init_prompts = __esm({
7856
+ "../../packages/companion-core/src/pipeline/prompts.ts"() {
7857
+ "use strict";
7858
+ OLLAMA_CHAT_MODEL = "qwen3:0.6b";
7859
+ OLLAMA_EMBED_MODEL = "bge-small-en-v1.5";
7860
+ SUMMARISER_SYSTEM_PROMPT = "You summarise an AI coding session in ONE sentence, \u2264 240 characters. Focus on what the human was trying to accomplish. No quotes, no PII, no code literals, no file paths. Reply with only the sentence.";
7861
+ SUMMARISER_MAX_TOKENS = 120;
7862
+ SUMMARISER_TEMPERATURE = 0.2;
7863
+ QWEN_CHARS_PER_TOKEN = 3.3;
5291
7864
  }
5292
7865
  });
5293
7866
 
5294
- // src/segment.ts
5295
- function summariseSessionEvents(session) {
5296
- const totalTokens = {
7867
+ // ../../packages/companion-core/src/pipeline/index.ts
7868
+ async function buildSegmentsForSession(events, adapters2) {
7869
+ if (events.length === 0) return [];
7870
+ const bySession = /* @__PURE__ */ new Map();
7871
+ for (const ev of events) {
7872
+ const arr = bySession.get(ev.session_id) ?? [];
7873
+ arr.push(ev);
7874
+ bySession.set(ev.session_id, arr);
7875
+ }
7876
+ const out = [];
7877
+ for (const [sessionId, evs] of bySession) {
7878
+ const segs = await buildForOneSession(sessionId, evs, adapters2);
7879
+ out.push(...segs);
7880
+ }
7881
+ return out;
7882
+ }
7883
+ async function buildForOneSession(sessionId, events, adapters2) {
7884
+ const sorted = [...events].sort((a, b) => a.ts.localeCompare(b.ts));
7885
+ const turnSurfaces = sorted.map((e) => turnSurface(e));
7886
+ const turnEmbeddings = [];
7887
+ for (const s of turnSurfaces) {
7888
+ turnEmbeddings.push(s.length > 0 ? await adapters2.embed(s) : []);
7889
+ }
7890
+ const boundaries = [];
7891
+ let runStart = 0;
7892
+ let runStartMs = Date.parse(sorted[0].ts);
7893
+ for (let i = 1; i < sorted.length; i++) {
7894
+ const prev2 = sorted[i - 1];
7895
+ const cur = sorted[i];
7896
+ const gap = Date.parse(cur.ts) - Date.parse(prev2.ts);
7897
+ const runMs = Date.parse(cur.ts) - runStartMs;
7898
+ const turnsInRun = i - runStart;
7899
+ let split = false;
7900
+ if (gap >= SEGMENT_TIME_GAP_MS) split = true;
7901
+ else if (turnsInRun >= SEGMENT_MAX_TURNS) split = true;
7902
+ else if (runMs >= SEGMENT_MAX_DURATION_MS) split = true;
7903
+ else if (turnEmbeddings[i - 1].length > 0 && turnEmbeddings[i].length > 0 && cosineDistance(turnEmbeddings[i - 1], turnEmbeddings[i]) > SEGMENT_TOPIC_THRESHOLD) {
7904
+ split = true;
7905
+ }
7906
+ if (split) {
7907
+ boundaries.push(i);
7908
+ runStart = i;
7909
+ runStartMs = Date.parse(cur.ts);
7910
+ }
7911
+ }
7912
+ boundaries.push(sorted.length);
7913
+ const slices = [];
7914
+ let prev = 0;
7915
+ for (const b of boundaries) {
7916
+ slices.push(sorted.slice(prev, b));
7917
+ prev = b;
7918
+ }
7919
+ const merged = [];
7920
+ for (const slice of slices) {
7921
+ const last = merged[merged.length - 1];
7922
+ if (slice.length === 1 && last) {
7923
+ last.push(...slice);
7924
+ } else {
7925
+ merged.push(slice);
7926
+ }
7927
+ }
7928
+ const segments = [];
7929
+ for (const slice of merged) {
7930
+ const seg = await summariseSlice(sessionId, slice, adapters2);
7931
+ if (seg) segments.push(seg);
7932
+ }
7933
+ return segments;
7934
+ }
7935
+ async function summariseSlice(sessionId, slice, adapters2) {
7936
+ if (slice.length === 0) return null;
7937
+ const first = slice[0];
7938
+ const last = slice[slice.length - 1];
7939
+ const startedAtMs = Date.parse(first.ts);
7940
+ const endedAtMs = Date.parse(last.ts);
7941
+ const tokens = {
5297
7942
  input: 0,
5298
7943
  output: 0,
5299
7944
  cache_creation: 0,
5300
7945
  cache_read: 0,
5301
7946
  reasoning: 0
5302
7947
  };
5303
- for (const e of session.events) {
5304
- if (!e.tokens) continue;
5305
- totalTokens.input += e.tokens.input;
5306
- totalTokens.output += e.tokens.output;
5307
- totalTokens.cache_creation += e.tokens.cache_creation;
5308
- totalTokens.cache_read += e.tokens.cache_read;
5309
- totalTokens.reasoning += e.tokens.reasoning;
5310
- }
5311
- const firstTyped = session.events.find((e) => e.kind !== "user_message");
5312
- const anyWithGit = session.events.find((e) => e.git?.remote_slug);
5313
- const anyWithCwd = session.events.find((e) => e.cwd);
5314
- const tool = firstTyped?.tool ?? session.events[0]?.tool ?? "unknown";
5315
- const provider = firstTyped?.provider ?? session.events[0]?.provider ?? "unknown";
5316
- const model = firstTyped?.model ?? session.events[0]?.model ?? null;
5317
- const branch = anyWithGit?.git?.branch ?? null;
5318
- const slug = anyWithGit?.git?.remote_slug ?? null;
5319
- const hints = [];
5320
- if (slug) {
5321
- hints.push({ root_key: "projects", name: slug, confidence: 1 });
5322
- }
5323
- hints.push({ root_key: "providers", name: provider, confidence: 1 });
5324
- if (model) hints.push({ root_key: "models", name: model, confidence: 1 });
5325
- hints.push({ root_key: "tools", name: tool, confidence: 1 });
5326
- const env = inferEnvironment(branch);
5327
- if (env) hints.push({ root_key: "environments", name: env, confidence: 0.7 });
5328
- const work = inferWorkType(branch);
5329
- if (work) hints.push({ root_key: "work_types", name: work, confidence: 0.6 });
5330
- const segment = {
5331
- idx: 0,
5332
- started_at: session.events[0]?.ts ?? null,
5333
- ended_at: session.events[session.events.length - 1]?.ts ?? null,
5334
- tokens: totalTokens,
5335
- turn_range: null,
5336
- goal: null,
5337
- feature: null,
5338
- work_type_hint: work,
5339
- domain_keywords: [],
5340
- taxonomy_hints: hints
5341
- };
5342
- return {
5343
- goal: null,
5344
- feature_hint: null,
5345
- work_type_hint: work,
5346
- domain_keywords: [],
5347
- segments: [segment],
5348
- redaction_report: {
5349
- secrets_found: 0,
5350
- emails_redacted: 0,
5351
- paths_redacted_absolute: 0
7948
+ for (const ev of slice) {
7949
+ if (!ev.tokens) continue;
7950
+ tokens.input += ev.tokens.input;
7951
+ tokens.output += ev.tokens.output;
7952
+ tokens.cache_creation += ev.tokens.cache_creation;
7953
+ tokens.cache_read += ev.tokens.cache_read;
7954
+ tokens.reasoning += ev.tokens.reasoning;
7955
+ }
7956
+ const promptFacts = [
7957
+ first.git?.remote_slug ? `repo ${first.git.remote_slug}` : null,
7958
+ first.git?.branch ? `branch ${first.git.branch}` : null,
7959
+ `${slice.length} turns on ${first.tool}`,
7960
+ first.files_touched?.length ? `files touched: ${first.files_touched.slice(0, 5).join(", ")}` : null,
7961
+ Object.keys(first.tool_calls ?? {}).length ? `tool calls: ${Object.keys(first.tool_calls).slice(0, 5).join(", ")}` : null
7962
+ ].filter(Boolean).join("; ");
7963
+ const prompt = `Session context: ${promptFacts || "generic coding session"}.
7964
+ Write one sentence describing what the human was doing.`;
7965
+ let rawAbstract;
7966
+ try {
7967
+ rawAbstract = await adapters2.summarize({ prompt, maxTokens: 80 });
7968
+ } catch {
7969
+ rawAbstract = promptFacts || `${first.tool} session with ${slice.length} turns`;
7970
+ }
7971
+ const redacted = redact(rawAbstract);
7972
+ const tags = [
7973
+ { root_key: "tools", name: first.tool, confidence: 1 },
7974
+ { root_key: "providers", name: first.provider, confidence: 1 }
7975
+ ];
7976
+ if (first.model) tags.push({ root_key: "models", name: first.model, confidence: 1 });
7977
+ if (first.git?.remote_slug) {
7978
+ tags.push({ root_key: "projects", name: first.git.remote_slug, confidence: 1 });
7979
+ }
7980
+ if (first.git?.branch) {
7981
+ const env = inferEnvironment(first.git.branch);
7982
+ if (env) tags.push({ root_key: "environments", name: env, confidence: 0.7 });
7983
+ }
7984
+ const components = /* @__PURE__ */ new Set();
7985
+ for (const ev of slice) {
7986
+ for (const f of ev.files_touched ?? []) {
7987
+ const seg = f.split("/").slice(0, 2).join("/");
7988
+ if (seg) components.add(seg);
5352
7989
  }
7990
+ }
7991
+ for (const c of [...components].slice(0, 8)) {
7992
+ tags.push({ root_key: "components", name: c, confidence: 0.6 });
7993
+ }
7994
+ let segmentEmbedding;
7995
+ try {
7996
+ const embedded = await adapters2.embed(redacted.text.slice(0, ABSTRACT_MAX_CHARS));
7997
+ if (embedded.length > 0) segmentEmbedding = embedded;
7998
+ } catch {
7999
+ segmentEmbedding = void 0;
8000
+ }
8001
+ const sourceEventIds = slice.map((e) => e.source_event_id);
8002
+ const id = segmentId(sessionId, startedAtMs, endedAtMs, sourceEventIds);
8003
+ return {
8004
+ segment_id: id,
8005
+ session_id: sessionId,
8006
+ tool: first.tool,
8007
+ started_at: first.ts,
8008
+ ended_at: last.ts,
8009
+ abstract: redacted.text.slice(0, ABSTRACT_MAX_CHARS),
8010
+ tokens,
8011
+ tags,
8012
+ redaction: redacted.counts,
8013
+ source_event_ids: sourceEventIds,
8014
+ abstract_embedding: segmentEmbedding && segmentEmbedding.length === 384 ? segmentEmbedding : void 0
5353
8015
  };
5354
8016
  }
8017
+ function turnSurface(e) {
8018
+ const parts = [e.kind, e.tool];
8019
+ if (e.model) parts.push(e.model);
8020
+ const toolCalls = Object.keys(e.tool_calls ?? {});
8021
+ if (toolCalls.length) parts.push(`tools:${toolCalls.join(",")}`);
8022
+ if (e.files_touched?.length) parts.push(`files:${e.files_touched.length}`);
8023
+ return parts.join(" ");
8024
+ }
8025
+ function cosineDistance(a, b) {
8026
+ let dot = 0;
8027
+ let na = 0;
8028
+ let nb = 0;
8029
+ const n = Math.min(a.length, b.length);
8030
+ for (let i = 0; i < n; i++) {
8031
+ dot += a[i] * b[i];
8032
+ na += a[i] * a[i];
8033
+ nb += b[i] * b[i];
8034
+ }
8035
+ const denom = Math.sqrt(na) * Math.sqrt(nb);
8036
+ return denom > 0 ? 1 - dot / denom : 1;
8037
+ }
5355
8038
  function inferEnvironment(branch) {
5356
- if (!branch) return null;
5357
8039
  const b = branch.toLowerCase();
5358
- if (b === "main" || b === "master" || b.startsWith("prod")) return "Production";
5359
- if (b.startsWith("staging") || b.startsWith("stage")) return "Staging";
5360
- if (b.startsWith("dev") || b === "develop" || b === "development") return "Development";
5361
- if (b.startsWith("test") || b.startsWith("qa")) return "Testing";
8040
+ if (b === "main" || b === "master" || b.startsWith("release/")) return "Prod";
8041
+ if (b === "staging" || b.startsWith("staging/")) return "Staging";
8042
+ if (b === "dev" || b === "develop" || b.startsWith("dev/")) return "Dev";
5362
8043
  return null;
5363
8044
  }
5364
- function inferWorkType(branch) {
5365
- if (!branch) return null;
5366
- for (const { work, re } of WORK_TYPE_PATTERNS) {
5367
- if (re.test(branch)) return work;
8045
+ var SEGMENT_TIME_GAP_MS, SEGMENT_TOPIC_THRESHOLD, SEGMENT_MAX_TURNS, SEGMENT_MAX_DURATION_MS, ABSTRACT_MAX_CHARS;
8046
+ var init_pipeline = __esm({
8047
+ "../../packages/companion-core/src/pipeline/index.ts"() {
8048
+ "use strict";
8049
+ init_redact();
8050
+ init_ids();
8051
+ init_redact();
8052
+ init_prompts();
8053
+ SEGMENT_TIME_GAP_MS = 15 * 6e4;
8054
+ SEGMENT_TOPIC_THRESHOLD = 0.35;
8055
+ SEGMENT_MAX_TURNS = 100;
8056
+ SEGMENT_MAX_DURATION_MS = 30 * 6e4;
8057
+ ABSTRACT_MAX_CHARS = 512;
5368
8058
  }
5369
- return null;
8059
+ });
8060
+
8061
+ // ../../packages/companion-core/src/index.ts
8062
+ var init_src3 = __esm({
8063
+ "../../packages/companion-core/src/index.ts"() {
8064
+ "use strict";
8065
+ init_contracts();
8066
+ init_ids2();
8067
+ init_logger();
8068
+ init_config();
8069
+ init_http();
8070
+ init_queue();
8071
+ init_pipeline();
8072
+ }
8073
+ });
8074
+
8075
+ // ../../packages/companion-core/src/node/file-queue-store.ts
8076
+ import { promises as fs } from "fs";
8077
+ import { dirname as dirname3 } from "path";
8078
+ var SENT_TTL_MS;
8079
+ var init_file_queue_store = __esm({
8080
+ "../../packages/companion-core/src/node/file-queue-store.ts"() {
8081
+ "use strict";
8082
+ SENT_TTL_MS = 24 * 60 * 60 * 1e3;
8083
+ }
8084
+ });
8085
+
8086
+ // ../../packages/companion-core/src/node/ollama.ts
8087
+ function defaultOllamaConfig() {
8088
+ const base = globalThis.process?.env ?? {};
8089
+ return {
8090
+ baseUrl: base.OLLAMA_URL ?? "http://localhost:11434",
8091
+ embedModel: base.OLLAMA_EMBED_MODEL ?? OLLAMA_EMBED_MODEL,
8092
+ chatModel: base.OLLAMA_CHAT_MODEL ?? OLLAMA_CHAT_MODEL
8093
+ };
8094
+ }
8095
+ function ollamaEmbed(cfg = defaultOllamaConfig()) {
8096
+ return async (text) => {
8097
+ const res = await fetch(`${cfg.baseUrl.replace(/\/+$/, "")}/api/embeddings`, {
8098
+ method: "POST",
8099
+ headers: { "content-type": "application/json" },
8100
+ body: JSON.stringify({ model: cfg.embedModel, prompt: text })
8101
+ });
8102
+ if (!res.ok) {
8103
+ throw new Error(`ollama embed failed: ${res.status} ${await res.text().catch(() => "")}`);
8104
+ }
8105
+ const body = await res.json();
8106
+ const v = body.embedding ?? [];
8107
+ let norm = 0;
8108
+ for (const x of v) norm += x * x;
8109
+ norm = Math.sqrt(norm) || 1;
8110
+ return v.map((x) => x / norm);
8111
+ };
8112
+ }
8113
+ function ollamaTokenize() {
8114
+ return (text) => Math.max(1, Math.ceil(text.length / QWEN_CHARS_PER_TOKEN));
8115
+ }
8116
+ function ollamaSummarize(cfg = defaultOllamaConfig()) {
8117
+ return async ({ prompt, maxTokens }) => {
8118
+ const res = await fetch(`${cfg.baseUrl.replace(/\/+$/, "")}/api/chat`, {
8119
+ method: "POST",
8120
+ headers: { "content-type": "application/json" },
8121
+ body: JSON.stringify({
8122
+ model: cfg.chatModel,
8123
+ stream: false,
8124
+ options: {
8125
+ temperature: SUMMARISER_TEMPERATURE,
8126
+ num_predict: Math.min(maxTokens, SUMMARISER_MAX_TOKENS)
8127
+ },
8128
+ messages: [
8129
+ { role: "system", content: SUMMARISER_SYSTEM_PROMPT },
8130
+ { role: "user", content: prompt }
8131
+ ]
8132
+ })
8133
+ });
8134
+ if (!res.ok) {
8135
+ throw new Error(`ollama summarize failed: ${res.status} ${await res.text().catch(() => "")}`);
8136
+ }
8137
+ const body = await res.json();
8138
+ return (body.message?.content ?? "").trim().slice(0, 240);
8139
+ };
5370
8140
  }
5371
- var WORK_TYPE_PATTERNS;
5372
- var init_segment = __esm({
5373
- "src/segment.ts"() {
8141
+ var init_ollama = __esm({
8142
+ "../../packages/companion-core/src/node/ollama.ts"() {
5374
8143
  "use strict";
5375
- WORK_TYPE_PATTERNS = [
5376
- { work: "debugging", re: /\b(fix|bug|debug|hotfix|incident|issue)\b/i },
5377
- { work: "testing", re: /\b(test|spec|e2e|ci)\b/i },
5378
- { work: "devops", re: /\b(deploy|infra|docker|k8s|terraform|helm|ci|cd)\b/i },
5379
- { work: "docs", re: /\b(docs|readme|guide|tutorial)\b/i },
5380
- { work: "refactoring", re: /\b(refactor|cleanup|lint|format)\b/i },
5381
- { work: "review", re: /\b(review|pr[-_]?\d+)\b/i },
5382
- { work: "planning", re: /\b(plan|design|rfc|spec)\b/i },
5383
- { work: "research", re: /\b(research|spike|prototype|explor)/i }
5384
- ];
8144
+ init_prompts();
8145
+ }
8146
+ });
8147
+
8148
+ // ../../packages/companion-core/src/node/index.ts
8149
+ var init_node = __esm({
8150
+ "../../packages/companion-core/src/node/index.ts"() {
8151
+ "use strict";
8152
+ init_file_queue_store();
8153
+ init_file_queue_store();
8154
+ init_ollama();
8155
+ }
8156
+ });
8157
+
8158
+ // src/pipeline.ts
8159
+ function getAdapters() {
8160
+ if (!adapters) {
8161
+ const cfg = defaultOllamaConfig();
8162
+ adapters = {
8163
+ embed: ollamaEmbed(cfg),
8164
+ summarize: ollamaSummarize(cfg),
8165
+ tokenize: ollamaTokenize()
8166
+ };
8167
+ }
8168
+ return adapters;
8169
+ }
8170
+ async function buildSegments(events) {
8171
+ return buildSegmentsForSession(events, getAdapters());
8172
+ }
8173
+ var adapters;
8174
+ var init_pipeline2 = __esm({
8175
+ "src/pipeline.ts"() {
8176
+ "use strict";
8177
+ init_pipeline();
8178
+ init_node();
8179
+ adapters = null;
5385
8180
  }
5386
8181
  });
5387
8182
 
@@ -5389,7 +8184,6 @@ var init_segment = __esm({
5389
8184
  import { readdir, stat as stat2 } from "fs/promises";
5390
8185
  import { homedir as homedir2 } from "os";
5391
8186
  import { join as join2 } from "path";
5392
- import { ulid as ulid2 } from "ulid";
5393
8187
  async function scanAll(cb = {}) {
5394
8188
  const deviceId = state.deviceId;
5395
8189
  if (!deviceId) throw new Error("agent not enrolled \u2014 run `register` first");
@@ -5450,25 +8244,14 @@ async function scanAll(cb = {}) {
5450
8244
  let buffer = [];
5451
8245
  async function flushBatch() {
5452
8246
  if (!buffer.length) return;
5453
- const n = buffer.length;
5454
- cb.onUpload?.(n);
5455
- const bySession = /* @__PURE__ */ new Map();
5456
- for (const e of buffer) {
5457
- const arr = bySession.get(e.session_id);
5458
- if (arr) arr.push(e);
5459
- else bySession.set(e.session_id, [e]);
5460
- }
5461
- const summaries = {};
5462
- for (const [sid, evs] of bySession.entries()) {
5463
- summaries[sid] = summariseSessionEvents({ sourceSessionId: sid, events: evs });
5464
- }
8247
+ cb.onUpload?.(buffer.length);
8248
+ const segments = await buildSegments(buffer);
5465
8249
  const batch = {
5466
- batch_id: ulid2(),
8250
+ batch_id: batchId(),
5467
8251
  device_id: deviceId,
5468
8252
  agent_version: AGENT_VERSION,
5469
- schema_version: 1,
5470
8253
  events: buffer,
5471
- session_summaries: summaries
8254
+ segments
5472
8255
  };
5473
8256
  const res = await uploadBatch(batch);
5474
8257
  batchesUploaded += 1;
@@ -5506,9 +8289,10 @@ var init_scan = __esm({
5506
8289
  "src/scan.ts"() {
5507
8290
  "use strict";
5508
8291
  init_src2();
5509
- init_config();
8292
+ init_src3();
8293
+ init_pipeline2();
8294
+ init_config2();
5510
8295
  init_api();
5511
- init_segment();
5512
8296
  AGENT_VERSION = "agent-dev-0.0.1";
5513
8297
  BATCH_MAX_EVENTS = 2e3;
5514
8298
  }
@@ -5684,7 +8468,7 @@ var init_daemon = __esm({
5684
8468
  "use strict";
5685
8469
  init_src2();
5686
8470
  init_api();
5687
- init_config();
8471
+ init_config2();
5688
8472
  init_scan();
5689
8473
  AGENT_VERSION2 = "agent-dev-0.0.1";
5690
8474
  HEARTBEAT_INTERVAL_MS = 1e4;
@@ -5797,11 +8581,11 @@ var init_watch = __esm({
5797
8581
  // src/cli.ts
5798
8582
  init_src2();
5799
8583
  init_api();
5800
- init_config();
8584
+ init_config2();
5801
8585
  init_scan();
5802
8586
  import { spawn } from "child_process";
8587
+ import { randomBytes } from "crypto";
5803
8588
  import { platform as platform4, release, arch as cpuArch, hostname as hostname2 } from "os";
5804
- import { setTimeout as delay } from "timers/promises";
5805
8589
 
5806
8590
  // src/service.ts
5807
8591
  import { spawnSync } from "child_process";
@@ -5813,7 +8597,7 @@ import {
5813
8597
  writeFileSync
5814
8598
  } from "fs";
5815
8599
  import { homedir as homedir3, platform as platform2, userInfo } from "os";
5816
- import { dirname as dirname3, join as join3 } from "path";
8600
+ import { dirname as dirname4, join as join3 } from "path";
5817
8601
  import { fileURLToPath as fileURLToPath2 } from "url";
5818
8602
  var SERVICE_LABEL = "ai.modelstat.agent";
5819
8603
  var SYSTEMD_UNIT = "modelstat";
@@ -5854,9 +8638,25 @@ function nodeBinary() {
5854
8638
  function plistPath() {
5855
8639
  return join3(home(), "Library", "LaunchAgents", `${SERVICE_LABEL}.plist`);
5856
8640
  }
8641
+ function locateTrayExecutable() {
8642
+ const candidates = [
8643
+ join3(home(), "Applications", "ModelstatTray.app", "Contents", "MacOS", "modelstat-tray"),
8644
+ "/Applications/ModelstatTray.app/Contents/MacOS/modelstat-tray"
8645
+ ];
8646
+ for (const p of candidates) {
8647
+ if (existsSync4(p)) return p;
8648
+ }
8649
+ return null;
8650
+ }
5857
8651
  function writePlist(cliPath) {
5858
8652
  const p = plistPath();
5859
- mkdirSync(dirname3(p), { recursive: true });
8653
+ mkdirSync(dirname4(p), { recursive: true });
8654
+ const tray = locateTrayExecutable();
8655
+ const programArgs = tray ? ` <string>${tray}</string>` : [
8656
+ ` <string>${nodeBinary()}</string>`,
8657
+ ` <string>${cliPath}</string>`,
8658
+ ` <string>start</string>`
8659
+ ].join("\n");
5860
8660
  const plist = `<?xml version="1.0" encoding="UTF-8"?>
5861
8661
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
5862
8662
  <plist version="1.0">
@@ -5864,9 +8664,7 @@ function writePlist(cliPath) {
5864
8664
  <key>Label</key><string>${SERVICE_LABEL}</string>
5865
8665
  <key>ProgramArguments</key>
5866
8666
  <array>
5867
- <string>${nodeBinary()}</string>
5868
- <string>${cliPath}</string>
5869
- <string>start</string>
8667
+ ${programArgs}
5870
8668
  </array>
5871
8669
  <key>RunAtLoad</key><true/>
5872
8670
  <key>KeepAlive</key>
@@ -5931,7 +8729,7 @@ function systemdUnitPath() {
5931
8729
  }
5932
8730
  function writeSystemdUnit(cliPath) {
5933
8731
  const unitPath = systemdUnitPath();
5934
- mkdirSync(dirname3(unitPath), { recursive: true });
8732
+ mkdirSync(dirname4(unitPath), { recursive: true });
5935
8733
  const unit = `[Unit]
5936
8734
  Description=modelstat agent
5937
8735
  Documentation=https://modelstat.ai
@@ -5943,7 +8741,7 @@ Type=simple
5943
8741
  ExecStart=${nodeBinary()} ${cliPath} start
5944
8742
  Restart=always
5945
8743
  RestartSec=10
5946
- # Don't restart-storm if the backend is persistently unreachable.
8744
+ # Don't restart-storm if the service is persistently unreachable.
5947
8745
  StartLimitIntervalSec=300
5948
8746
  StartLimitBurst=10
5949
8747
  StandardOutput=append:${join3(logDir(), "out.log")}
@@ -6014,6 +8812,55 @@ function serviceStatus() {
6014
8812
  function logsDir() {
6015
8813
  return logDir();
6016
8814
  }
8815
+ function installTrayApp(sourceAppPath) {
8816
+ if (platform2() !== "darwin") return null;
8817
+ if (!existsSync4(sourceAppPath)) return null;
8818
+ const dest = join3(home(), "Applications", "ModelstatTray.app");
8819
+ mkdirSync(dirname4(dest), { recursive: true });
8820
+ spawnSync("rm", ["-rf", dest]);
8821
+ const r = spawnSync("cp", ["-R", sourceAppPath, dest], { encoding: "utf8" });
8822
+ if (r.status !== 0) {
8823
+ throw new Error(`cp ModelstatTray.app failed: ${r.stderr?.trim() || `exit ${r.status}`}`);
8824
+ }
8825
+ return { installedAt: dest };
8826
+ }
8827
+ function bundledTrayAppPath() {
8828
+ if (platform2() !== "darwin") return null;
8829
+ const here2 = dirname4(fileURLToPath2(import.meta.url));
8830
+ const candidates = [
8831
+ // Pre-built .app — CI with codesigning drops one here.
8832
+ join3(here2, "..", "vendor", "ModelstatTray.app"),
8833
+ // Local dev layout: apps/agent-dev/src/service.ts → ../../tray-mac/build/ModelstatTray.app
8834
+ join3(here2, "..", "..", "tray-mac", "build", "ModelstatTray.app")
8835
+ ];
8836
+ for (const c of candidates) {
8837
+ if (existsSync4(c)) return c;
8838
+ }
8839
+ const sourceDirs = [
8840
+ join3(here2, "..", "vendor", "tray-mac"),
8841
+ join3(here2, "..", "..", "tray-mac")
8842
+ ];
8843
+ for (const src of sourceDirs) {
8844
+ const build = join3(src, "build-app.sh");
8845
+ if (!existsSync4(build)) continue;
8846
+ if (!hasSwift()) return null;
8847
+ const r = spawnSync("bash", [build], { cwd: src, encoding: "utf8" });
8848
+ if (r.status === 0) {
8849
+ const app = join3(src, "build", "ModelstatTray.app");
8850
+ if (existsSync4(app)) return app;
8851
+ }
8852
+ }
8853
+ return null;
8854
+ }
8855
+ function hasSwift() {
8856
+ const r = spawnSync("swift", ["--version"], { encoding: "utf8" });
8857
+ return r.status === 0;
8858
+ }
8859
+ function trayStatus() {
8860
+ if (platform2() !== "darwin") return { installed: false, path: null };
8861
+ const exe = locateTrayExecutable();
8862
+ return exe ? { installed: true, path: exe.replace(/\/Contents\/MacOS\/modelstat-tray$/, "") } : { installed: false, path: null };
8863
+ }
6017
8864
 
6018
8865
  // src/cli.ts
6019
8866
  function tryOpenBrowser(url) {
@@ -6044,122 +8891,168 @@ function osArch() {
6044
8891
  if (a === "arm64") return "arm64";
6045
8892
  return "other";
6046
8893
  }
6047
- async function cmdRegister() {
6048
- const email = defaultUserEmail();
6049
- const res = await enrollDevice({
6050
- machine_id: machineId(),
8894
+ function generateUuidV7() {
8895
+ const ms = Date.now();
8896
+ const tsHex = ms.toString(16).padStart(12, "0");
8897
+ const rand = randomBytes(10);
8898
+ rand[0] = rand[0] & 15 | 112;
8899
+ rand[2] = rand[2] & 63 | 128;
8900
+ const hex = tsHex + rand.toString("hex");
8901
+ return [
8902
+ hex.slice(0, 8),
8903
+ hex.slice(8, 12),
8904
+ hex.slice(12, 16),
8905
+ hex.slice(16, 20),
8906
+ hex.slice(20, 32)
8907
+ ].join("-");
8908
+ }
8909
+ async function cmdSelfRegister() {
8910
+ const deviceUuid = state.deviceUuid ?? generateUuidV7();
8911
+ const fingerprint = {
6051
8912
  hostname: hostname2(),
6052
8913
  os_family: osFamily(),
6053
8914
  os_version: release(),
6054
8915
  arch: osArch(),
6055
- agent_version: AGENT_VERSION3,
6056
- user_email: email
8916
+ agent: "modelstat-agent-dev",
8917
+ agent_version: AGENT_VERSION3
8918
+ };
8919
+ const res = await selfRegister({
8920
+ device_uuid: deviceUuid,
8921
+ fingerprint
6057
8922
  });
6058
- state.setBearer(res.bearer_token);
8923
+ state.setDeviceUuid(res.device_uuid);
6059
8924
  state.setDeviceId(res.device_id);
6060
- state.setUserEmail(email);
6061
- console.log(`\u2713 device enrolled (dev-shortcut)`);
6062
- console.log(` user_id: ${res.user_id}`);
6063
- console.log(` device_id: ${res.device_id}`);
6064
- console.log(` bearer: ${res.bearer_token.slice(0, 16)}\u2026`);
6065
- console.log(` state: ${state.storePath}`);
6066
- }
6067
- async function cmdConnect() {
6068
- const init = await startDeviceCode();
6069
- const url = init.verification_url;
6070
- const opened = tryOpenBrowser(url);
6071
- const line = "\u2501".repeat(60);
8925
+ state.setBearer(res.device_secret);
8926
+ state.setClaimCode(res.claim_code);
8927
+ state.setClaimUrl(res.claim_url);
8928
+ console.log(`\u2713 self-registered`);
8929
+ console.log(` device_uuid: ${res.device_uuid}`);
8930
+ console.log(` device_id: ${res.device_id}`);
8931
+ console.log(` secret_prefix: ${res.secret_prefix}\u2026`);
6072
8932
  console.log();
6073
- console.log(line);
6074
- console.log(
6075
- opened ? " Opening your browser to approve this device\u2026" : " Open this URL in any browser to approve this device:"
6076
- );
6077
- console.log();
6078
- console.log(` \x1B[1;36m${url}\x1B[0m`);
6079
- console.log();
6080
- console.log(" Pairing code (if you'd rather type it manually):");
8933
+ console.log(` Claim this device to attach it to your account:`);
8934
+ console.log(` ${res.claim_url}`);
8935
+ console.log(` code: ${res.claim_code}`);
6081
8936
  console.log();
6082
- console.log(` \x1B[1;33m${init.user_code}\x1B[0m`);
6083
- console.log();
6084
- console.log(` Waiting for approval (expires in ${init.expires_in}s)`);
6085
- console.log(line);
6086
- console.log();
6087
- const deadline = Date.now() + init.expires_in * 1e3;
6088
- let dots = 0;
6089
- while (Date.now() < deadline) {
6090
- await delay(init.interval * 1e3);
8937
+ console.log(` state: ${state.storePath}`);
8938
+ }
8939
+ async function cmdAwaitClaim() {
8940
+ const secret = state.bearer;
8941
+ if (!secret) {
8942
+ console.error("not registered \u2014 run `modelstat self-register` first");
8943
+ process.exit(1);
8944
+ }
8945
+ const url = state.claimUrl ?? "(visit your dashboard)";
8946
+ console.log(`waiting for human to claim this device:
8947
+ ${url}
8948
+ `);
8949
+ while (true) {
8950
+ let me;
6091
8951
  try {
6092
- const res = await pollDeviceCode(init.device_code);
6093
- if (res.status === "approved") {
6094
- state.setBearer(res.bearer_token);
6095
- state.setUserEmail(`user:${res.user_id}`);
6096
- console.log();
6097
- console.log("\u2713 approved \u2014 bearer stored");
6098
- let enroll = null;
6099
- try {
6100
- enroll = await enrollDevice({
6101
- machine_id: machineId(),
6102
- hostname: hostname2(),
6103
- os_family: osFamily(),
6104
- os_version: release(),
6105
- arch: osArch(),
6106
- agent_version: AGENT_VERSION3
6107
- });
6108
- } catch (e) {
6109
- console.error();
6110
- console.error(`\u2717 device enrollment failed: ${e.message}`);
6111
- console.error(
6112
- " The approval went through but the server couldn't register this"
6113
- );
6114
- console.error(
6115
- " machine. Check that your modelstat API is reachable at"
6116
- );
6117
- console.error(` ${state.apiUrl} \u2014 then run \`modelstat connect\` again.`);
6118
- process.exit(1);
6119
- }
6120
- if (!enroll?.device_id) {
6121
- console.error("\n\u2717 enrollment returned no device_id. Aborting.");
6122
- process.exit(1);
6123
- }
6124
- state.setDeviceId(enroll.device_id);
6125
- console.log(`\u2713 device registered (${enroll.device_id.slice(0, 8)}\u2026)`);
6126
- try {
6127
- const svc = installService();
6128
- console.log(`\u2713 service installed (${svc.path})`);
6129
- console.log(` logs: ${svc.logs}`);
6130
- console.log();
6131
- const banner = "\u2501".repeat(60);
6132
- console.log(banner);
6133
- console.log(" You're connected. The agent is now running in the");
6134
- console.log(" background and will start on login.");
6135
- console.log();
6136
- console.log(" Manage it from the dashboard:");
6137
- console.log(" \x1B[1;36mhttps://modelstat.ai/dashboard\x1B[0m");
6138
- console.log();
6139
- console.log(" Stop it any time: \x1B[2mmodelstat stop\x1B[0m");
6140
- console.log(" Uninstall: \x1B[2mmodelstat uninstall\x1B[0m");
6141
- console.log(banner);
6142
- return;
6143
- } catch (err) {
6144
- console.warn();
6145
- console.warn(`\u26A0 couldn't install as a background service: ${err.message}`);
6146
- console.warn(" Running in the foreground instead \u2014 press Ctrl-C to stop.");
6147
- console.warn(" (Install globally with `npm i -g modelstat` then re-run `modelstat connect`.)");
6148
- console.warn();
6149
- const { runDaemon: runDaemon2 } = await Promise.resolve().then(() => (init_daemon(), daemon_exports));
6150
- await runDaemon2();
6151
- return;
6152
- }
6153
- }
8952
+ me = await fetchDeviceMe(secret);
6154
8953
  } catch (e) {
6155
- if (dots % 15 === 0) console.warn(`
6156
- [retry] ${e.message}`);
8954
+ console.error(`poll failed: ${e.message}`);
8955
+ await new Promise((r) => setTimeout(r, 5e3));
8956
+ continue;
8957
+ }
8958
+ if (me.status === "claimed") {
8959
+ console.log(`\u2713 claimed by user_id=${me.user_id}`);
8960
+ return;
6157
8961
  }
6158
- dots += 1;
6159
8962
  process.stdout.write(".");
8963
+ await new Promise((r) => setTimeout(r, 2e3));
6160
8964
  }
6161
- console.error("\ndevice_code expired before approval");
6162
- process.exit(1);
8965
+ }
8966
+ function emitEvent(opts, event, fields = {}) {
8967
+ if (!opts.json) return;
8968
+ process.stdout.write(
8969
+ `${JSON.stringify({ v: 1, ts: Date.now(), event, ...fields })}
8970
+ `
8971
+ );
8972
+ }
8973
+ async function cmdConnect(opts) {
8974
+ if (!state.deviceUuid || !state.bearer || !state.deviceId) {
8975
+ await cmdSelfRegister();
8976
+ }
8977
+ const claimCode = state.claimCode ?? "(unknown)";
8978
+ const claimUrl = state.claimUrl ?? `https://modelstat.ai/d/${claimCode}`;
8979
+ const agentUrl = `https://modelstat.ai/da/${claimCode}`;
8980
+ emitEvent(opts, "registered", {
8981
+ device_uuid: state.deviceUuid,
8982
+ device_id: state.deviceId,
8983
+ claim_code: claimCode,
8984
+ claim_url: claimUrl,
8985
+ agent_url: agentUrl
8986
+ });
8987
+ if (platform4() === "darwin") {
8988
+ try {
8989
+ const src = bundledTrayAppPath();
8990
+ if (src) {
8991
+ const out = installTrayApp(src);
8992
+ if (out) emitEvent(opts, "tray_installed", { path: out.installedAt });
8993
+ } else {
8994
+ emitEvent(opts, "tray_not_bundled", {});
8995
+ }
8996
+ } catch (e) {
8997
+ emitEvent(opts, "tray_install_failed", { error: e.message });
8998
+ }
8999
+ }
9000
+ let serviceOk = false;
9001
+ try {
9002
+ const svc = installService();
9003
+ serviceOk = true;
9004
+ emitEvent(opts, "service_installed", { path: svc.path, logs: svc.logs });
9005
+ } catch (e) {
9006
+ emitEvent(opts, "service_install_failed", { error: e.message });
9007
+ }
9008
+ if (!opts.json) {
9009
+ const tray = trayStatus();
9010
+ const svcOk = serviceOk;
9011
+ const line = "\u2501".repeat(60);
9012
+ console.log();
9013
+ console.log(line);
9014
+ console.log(` \u2713 Device registered \u2014 streaming your AI usage to modelstat.`);
9015
+ console.log();
9016
+ console.log(
9017
+ ` service : \x1B[${svcOk ? "32" : "33"}m${svcOk ? "installed" : "foreground"}\x1B[0m`
9018
+ );
9019
+ if (platform4() === "darwin") {
9020
+ console.log(
9021
+ ` tray : \x1B[${tray.installed ? "32" : "2"}m${tray.installed ? "menu-bar icon ready" : "not installed"}\x1B[0m`
9022
+ );
9023
+ }
9024
+ console.log();
9025
+ console.log(` Open your dashboard (no sign-up needed):`);
9026
+ console.log(` \x1B[1;36m${claimUrl}\x1B[0m`);
9027
+ console.log();
9028
+ console.log(` Live numbers from this terminal:`);
9029
+ console.log(` \x1B[2mmodelstat stats\x1B[0m # sessions \xB7 tokens \xB7 cost`);
9030
+ console.log(` \x1B[2mmodelstat jobs\x1B[0m # pipeline queue + recent activity`);
9031
+ console.log();
9032
+ console.log(` Agent-friendly (for LLMs / MCPs):`);
9033
+ console.log(` \x1B[2m${agentUrl}\x1B[0m`);
9034
+ console.log();
9035
+ console.log(` Claim this device so it keeps analyzing past 100M tokens/mo:`);
9036
+ console.log(` \x1B[2m${claimUrl}/claim\x1B[0m`);
9037
+ console.log(line);
9038
+ console.log();
9039
+ }
9040
+ if (!opts.noBrowser) {
9041
+ const opened = tryOpenBrowser(claimUrl);
9042
+ emitEvent(opts, "browser_open_attempted", { opened });
9043
+ }
9044
+ emitEvent(opts, "done", { claim_url: claimUrl, agent_url: agentUrl });
9045
+ if (serviceOk) {
9046
+ return;
9047
+ }
9048
+ if (opts.json) {
9049
+ return;
9050
+ }
9051
+ console.log(" Service install not supported on this platform \u2014 running in foreground.");
9052
+ console.log(" Press Ctrl-C to stop.");
9053
+ console.log();
9054
+ const { runDaemon: runDaemon2 } = await Promise.resolve().then(() => (init_daemon(), daemon_exports));
9055
+ await runDaemon2();
6163
9056
  }
6164
9057
  async function cmdDiscover() {
6165
9058
  const deviceId = state.deviceId;
@@ -6211,22 +9104,157 @@ async function cmdStatus() {
6211
9104
  if (paired) {
6212
9105
  console.log(` user: ${state.userEmail ?? "(unknown)"}`);
6213
9106
  console.log(` device: ${state.deviceId}`);
9107
+ console.log(` uuid: ${state.deviceUuid ?? "(not self-registered)"}`);
6214
9108
  }
6215
9109
  console.log(`service: ${s.running ? "running" : "stopped"} (${s.hint})`);
6216
9110
  console.log(`logs: ${logsDir()}`);
6217
9111
  console.log(`state: ${state.storePath}`);
9112
+ console.log(`api: ${state.apiUrl}`);
9113
+ }
9114
+ function fmtInt(n) {
9115
+ return Number(n).toLocaleString("en-US");
9116
+ }
9117
+ function fmtCost(usd) {
9118
+ return `$${usd.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
9119
+ }
9120
+ function fmtTokens(v) {
9121
+ const n = typeof v === "string" ? Number(v) : v;
9122
+ if (!Number.isFinite(n)) return "\u2014";
9123
+ if (n >= 1e9) return `${(n / 1e9).toFixed(n >= 1e10 ? 0 : 1)}B`;
9124
+ if (n >= 1e6) return `${(n / 1e6).toFixed(n >= 1e7 ? 0 : 1)}M`;
9125
+ if (n >= 1e3) return `${(n / 1e3).toFixed(0)}K`;
9126
+ return String(n);
9127
+ }
9128
+ async function cmdStats(args) {
9129
+ const asJson = args.includes("--json");
9130
+ const claim = state.claimCode;
9131
+ if (!claim) {
9132
+ if (asJson) {
9133
+ process.stdout.write(`${JSON.stringify({ paired: false, reason: "no_claim_code" })}
9134
+ `);
9135
+ } else {
9136
+ console.log("no claim code on record \u2014 run `modelstat connect` first");
9137
+ }
9138
+ return;
9139
+ }
9140
+ const view = await fetchDeviceViewByClaim(claim);
9141
+ if (!view) {
9142
+ const dashboard = `${state.apiUrl.replace(/\/$/, "")}/dashboard`;
9143
+ if (asJson) {
9144
+ process.stdout.write(
9145
+ `${JSON.stringify({ paired: true, claimed: true, dashboard })}
9146
+ `
9147
+ );
9148
+ } else {
9149
+ console.log("device is claimed \u2014 live stats available at:");
9150
+ console.log(` ${dashboard}`);
9151
+ }
9152
+ return;
9153
+ }
9154
+ if (asJson) {
9155
+ process.stdout.write(`${JSON.stringify(view)}
9156
+ `);
9157
+ return;
9158
+ }
9159
+ console.log(`device: ${view.device.id}`);
9160
+ console.log(`host: ${view.device.hostname ?? "(unknown)"} (${view.device.os_family ?? "?"})`);
9161
+ console.log(`agent: ${view.device.agent_version ?? "(unknown)"}`);
9162
+ console.log(
9163
+ `status: ${view.device.agent_status ?? "(unknown)"}${view.device.last_seen_at ? ` \xB7 last seen ${view.device.last_seen_at}` : ""}`
9164
+ );
9165
+ console.log(`claim: ${view.status}${view.status === "unclaimed" ? ` (at ${view.claim_url})` : ""}`);
9166
+ console.log(`sessions: ${fmtInt(view.analyzed.count)}`);
9167
+ console.log(`tokens: ${fmtTokens(view.analyzed.totalTokens)}`);
9168
+ console.log(`cost: ${fmtCost(view.analyzed.totalCostUsd)}`);
9169
+ console.log(`quota: ${fmtTokens(view.free_quota_tokens)} free-tier ceiling`);
9170
+ }
9171
+ async function cmdJobs(args) {
9172
+ const asJson = args.includes("--json");
9173
+ const claim = state.claimCode;
9174
+ if (!claim) {
9175
+ if (asJson) {
9176
+ process.stdout.write(`${JSON.stringify({ paired: false, reason: "no_claim_code" })}
9177
+ `);
9178
+ } else {
9179
+ console.log("no claim code on record \u2014 run `modelstat connect` first");
9180
+ }
9181
+ return;
9182
+ }
9183
+ const [jobs, ledger] = await Promise.all([
9184
+ fetchDeviceViewJobsByClaim(claim),
9185
+ fetchDeviceViewLedgerByClaim(claim)
9186
+ ]);
9187
+ if (!jobs && !ledger) {
9188
+ const dashboard = `${state.apiUrl.replace(/\/$/, "")}/dashboard/jobs`;
9189
+ if (asJson) {
9190
+ process.stdout.write(
9191
+ `${JSON.stringify({ paired: true, claimed: true, dashboard })}
9192
+ `
9193
+ );
9194
+ } else {
9195
+ console.log("device is claimed \u2014 job queue at:");
9196
+ console.log(` ${dashboard}`);
9197
+ }
9198
+ return;
9199
+ }
9200
+ if (asJson) {
9201
+ process.stdout.write(
9202
+ `${JSON.stringify({ jobs: jobs ?? null, ledger: ledger?.recent ?? [] })}
9203
+ `
9204
+ );
9205
+ return;
9206
+ }
9207
+ console.log(`queue: ${jobs?.pending ?? 0} pending \xB7 ${jobs?.running ?? 0} running`);
9208
+ const recent = ledger?.recent ?? [];
9209
+ if (recent.length === 0) {
9210
+ console.log("ledger: (no activity yet)");
9211
+ return;
9212
+ }
9213
+ console.log(`ledger: (last ${recent.length})`);
9214
+ for (const r of recent.slice(0, 15)) {
9215
+ const ts = r.occurred_at.slice(0, 19).replace("T", " ");
9216
+ console.log(
9217
+ ` ${ts} ${r.kind.padEnd(16)} ${fmtTokens(r.tokens).padStart(7)} tok ${r.session_id ?? ""}`
9218
+ );
9219
+ }
9220
+ }
9221
+ function cmdPaths(args) {
9222
+ const data = {
9223
+ state: state.storePath,
9224
+ logs: logsDir(),
9225
+ api: state.apiUrl,
9226
+ paired: !!state.bearer && !!state.deviceId
9227
+ };
9228
+ if (args.includes("--json")) {
9229
+ process.stdout.write(`${JSON.stringify(data)}
9230
+ `);
9231
+ return;
9232
+ }
9233
+ for (const [k, v] of Object.entries(data)) {
9234
+ console.log(`${k.padEnd(8)} ${String(v)}`);
9235
+ }
9236
+ }
9237
+ function parseConnectOpts(argv) {
9238
+ return {
9239
+ json: argv.includes("--json"),
9240
+ noBrowser: argv.includes("--no-browser")
9241
+ };
6218
9242
  }
6219
9243
  async function main() {
6220
9244
  const cmd = process.argv[2];
9245
+ const rest = process.argv.slice(3);
6221
9246
  switch (cmd) {
6222
9247
  case void 0:
6223
9248
  case "start":
6224
- if (!state.bearer || !state.deviceId) return cmdConnect();
9249
+ if (!state.bearer || !state.deviceId)
9250
+ return cmdConnect(parseConnectOpts(rest));
6225
9251
  return cmdStart();
6226
9252
  case "connect":
6227
- return cmdConnect();
6228
- case "register":
6229
- return cmdRegister();
9253
+ return cmdConnect(parseConnectOpts(rest));
9254
+ case "self-register":
9255
+ return cmdSelfRegister();
9256
+ case "await-claim":
9257
+ return cmdAwaitClaim();
6230
9258
  case "discover":
6231
9259
  return cmdDiscover();
6232
9260
  case "scan":
@@ -6238,20 +9266,32 @@ async function main() {
6238
9266
  return cmdStop();
6239
9267
  case "status":
6240
9268
  return cmdStatus();
9269
+ case "stats":
9270
+ return cmdStats(rest);
9271
+ case "jobs":
9272
+ return cmdJobs(rest);
9273
+ case "paths":
9274
+ cmdPaths(rest);
9275
+ return;
6241
9276
  default:
6242
9277
  console.log(
6243
- "usage: modelstat [connect|status|stop|start|discover|scan|watch|register]"
9278
+ "usage: modelstat [connect|self-register|await-claim|status|stats|jobs|paths|stop|start|discover|scan|watch]"
6244
9279
  );
6245
9280
  console.log();
6246
- console.log(" (no args) \u2014 pair if needed, then run the daemon in the foreground");
6247
- console.log(" connect \u2014 pair + install as a background service, then exit");
6248
- console.log(" status \u2014 show pairing + service state");
6249
- console.log(" stop \u2014 stop and uninstall the background service");
6250
- console.log(" start \u2014 run the daemon (used by the installed service)");
6251
- console.log(" discover \u2014 one-shot report of installs/identities");
6252
- console.log(" scan \u2014 one-shot parse + upload of local JSONL");
6253
- console.log(" watch \u2014 continuous (chokidar) with periodic backstop");
6254
- console.log(" register \u2014 DEV shortcut (email-only, no OAuth)");
9281
+ console.log(" (no args) \u2014 pair if needed, then run the daemon in the foreground");
9282
+ console.log(" connect \u2014 self-register + install the background service; prints /d/:claim_code URL");
9283
+ console.log(" flags: --json (NDJSON events on stdout), --no-browser");
9284
+ console.log(" self-register \u2014 generate UUIDv7 + register; print claim URL and exit");
9285
+ console.log(" await-claim \u2014 block until a human claims this self-registered device");
9286
+ console.log(" status \u2014 show pairing + service state");
9287
+ console.log(" stats \u2014 live device summary: sessions, tokens, cost (use --json)");
9288
+ console.log(" jobs \u2014 pipeline queue + recent processing ledger (use --json)");
9289
+ console.log(" paths \u2014 print state file + log dir + api URL (use --json for machine-readable)");
9290
+ console.log(" stop \u2014 stop and uninstall the background service");
9291
+ console.log(" start \u2014 run the daemon (used by the installed service)");
9292
+ console.log(" discover \u2014 one-shot report of installs/identities");
9293
+ console.log(" scan \u2014 one-shot parse + upload of local JSONL");
9294
+ console.log(" watch \u2014 continuous (chokidar) with periodic backstop");
6255
9295
  process.exit(1);
6256
9296
  }
6257
9297
  }