@r-33/opencode 0.4.7-rc.23 → 0.4.7-rc.25

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.
@@ -2553,7 +2553,7 @@ var createLeaseInstallationFactory = (options) => {
2553
2553
  return existing;
2554
2554
  }
2555
2555
  const installation = {
2556
- keyName: `route33:lease:${scopeId}`,
2556
+ keyName: `route33_lease_${scopeId}`,
2557
2557
  secretStore: options.createSecretStore(scopeId),
2558
2558
  ...options.createStateStore === void 0 ? {} : { stateStore: options.createStateStore(scopeId) },
2559
2559
  state: LeaseState.restore(void 0)
@@ -2720,7 +2720,7 @@ import {
2720
2720
  } from "@r-33/auth-browser";
2721
2721
 
2722
2722
  // src/requested-scopes/requested-scopes.ts
2723
- var REQUESTED_OAUTH_SCOPES = "openid offline_access orgs:read projects:read keys:read keys:write";
2723
+ var REQUESTED_OAUTH_SCOPES = "openid offline_access orgs:read projects:read users:read keys:read keys:write";
2724
2724
 
2725
2725
  // src/route33-login/route33-login.ts
2726
2726
  var route33Login = async (options) => {
@@ -2865,6 +2865,56 @@ var Route33Runtime = class {
2865
2865
  login(policy = {}) {
2866
2866
  return this.#session.result(policy);
2867
2867
  }
2868
+ /**
2869
+ * Lists exactly the projects the current management login can mint keys
2870
+ * on: the login's per-user budget rows intersected with the
2871
+ * member-visible project listing, organisation names stitched from the
2872
+ * login's own memberships. Orgs the login merely administers carry no
2873
+ * budget row and drop out — the picker never offers a project whose
2874
+ * keys the login cannot create. A `allowBrowser: false` policy makes
2875
+ * the call non-blocking: a dead session rejects instead of opening a
2876
+ * browser, so the picker's form registration never stalls a boot.
2877
+ * @param policy - Whether a dead session may open a browser login.
2878
+ * @returns Mintable projects with organisation context for the picker.
2879
+ */
2880
+ async listMintableProjects(policy = {}) {
2881
+ const credential = await this.#session.credential(policy);
2882
+ const subject = this.#subject(credential);
2883
+ const client = this.#client();
2884
+ const [budgets, memberships] = await Promise.all([
2885
+ client.listProjectBudgets(credential, subject),
2886
+ client.listMemberships(credential, subject)
2887
+ ]);
2888
+ const organisationNames = new Map(
2889
+ memberships.org_memberships.map(({ org_id, org_name }) => [
2890
+ org_id,
2891
+ org_name
2892
+ ])
2893
+ );
2894
+ const listings = await Promise.all(
2895
+ [...new Set(budgets.data.map(({ org_id }) => org_id))].map(
2896
+ (orgId) => client.listProjects(credential, orgId)
2897
+ )
2898
+ );
2899
+ const projectsById = new Map(
2900
+ listings.flatMap(({ data }) => data).map((project) => [project.id, project])
2901
+ );
2902
+ return budgets.data.flatMap(({ org_id, project_id }) => {
2903
+ const project = projectsById.get(project_id);
2904
+ if (project === void 0) {
2905
+ return [];
2906
+ }
2907
+ return [
2908
+ {
2909
+ ...project,
2910
+ organisation: {
2911
+ id: org_id,
2912
+ name: organisationNames.get(org_id) ?? org_id
2913
+ }
2914
+ }
2915
+ ];
2916
+ });
2917
+ }
2868
2918
  /**
2869
2919
  * Lists projects visible to the current management login.
2870
2920
  * @returns Projects with their listing organisation stitched in.
@@ -3104,7 +3154,7 @@ var Route33Runtime = class {
3104
3154
  return resolveAttribution({
3105
3155
  loadProjects: async () => {
3106
3156
  await this.#session.credential();
3107
- return this.listProjects();
3157
+ return this.listMintableProjects();
3108
3158
  },
3109
3159
  ...this.#options.presenter === void 0 ? {} : { presenter: this.#options.presenter },
3110
3160
  state: this.#options.state
@@ -3271,6 +3321,34 @@ var createRoute33Plugin = (options = {}) => {
3271
3321
  // src/production-runtime-options/production-runtime-options.ts
3272
3322
  import { createAuthSession } from "@r-33/auth-browser";
3273
3323
 
3324
+ // src/management/drain-pages/drain-pages.ts
3325
+ var drainPages = async (fetchPage) => {
3326
+ const first = await fetchPage("");
3327
+ const data = [...first.data];
3328
+ let { page } = first;
3329
+ while (page.has_more && page.next_cursor !== null) {
3330
+ const next = await fetchPage(page.next_cursor);
3331
+ data.push(...next.data);
3332
+ ({ page } = next);
3333
+ }
3334
+ return { data, page: { ...page, has_more: false, next_cursor: null } };
3335
+ };
3336
+
3337
+ // src/management/management-error/management-error.ts
3338
+ var ManagementError = class extends Error {
3339
+ constructor(code, options) {
3340
+ super(
3341
+ "Route 33 management request failed",
3342
+ options?.cause === void 0 ? void 0 : { cause: "Route 33 management dependency failed" }
3343
+ );
3344
+ this.code = code;
3345
+ this.name = "ManagementError";
3346
+ this.statusCode = options?.statusCode;
3347
+ }
3348
+ code;
3349
+ statusCode;
3350
+ };
3351
+
3274
3352
  // src/management/sdk-management-keys/sdk-management-keys.ts
3275
3353
  import {
3276
3354
  createRoute33Client,
@@ -3438,6 +3516,39 @@ var parseOrganization = (value) => {
3438
3516
  };
3439
3517
  };
3440
3518
 
3519
+ // src/contract/management-keys/parse-project-budget-state/parse-project-budget-state.ts
3520
+ var parseProjectBudgetState = (value) => {
3521
+ if (!isRecord(value)) {
3522
+ throw new ContractParseError("invalid project budget");
3523
+ }
3524
+ const stringField = (name) => {
3525
+ const field = value[name];
3526
+ if (typeof field !== "string") {
3527
+ throw new ContractParseError("invalid project budget");
3528
+ }
3529
+ return field;
3530
+ };
3531
+ const cap = value["cap"];
3532
+ if (typeof cap !== "number") {
3533
+ throw new ContractParseError("invalid project budget");
3534
+ }
3535
+ const hasUsage = value["has_usage"];
3536
+ if (typeof hasUsage !== "boolean") {
3537
+ throw new ContractParseError("invalid project budget");
3538
+ }
3539
+ const source = value["source"];
3540
+ if (source !== "own_cap" && source !== "project_default" && source !== "org_default" && source !== "tenant_default" && source !== "platform_default") {
3541
+ throw new ContractParseError("invalid project budget");
3542
+ }
3543
+ return {
3544
+ cap,
3545
+ has_usage: hasUsage,
3546
+ org_id: stringField("org_id"),
3547
+ project_id: stringField("project_id"),
3548
+ source
3549
+ };
3550
+ };
3551
+
3441
3552
  // src/contract/management-keys/parse-wire-money/parse-wire-money.ts
3442
3553
  var parseWireMoney = (value) => {
3443
3554
  if (!isRecord(value)) return null;
@@ -3460,19 +3571,28 @@ var parseProject = (value) => {
3460
3571
  };
3461
3572
  };
3462
3573
 
3463
- // src/management/management-error/management-error.ts
3464
- var ManagementError = class extends Error {
3465
- constructor(code, options) {
3466
- super(
3467
- "Route 33 management request failed",
3468
- options?.cause === void 0 ? void 0 : { cause: "Route 33 management dependency failed" }
3469
- );
3470
- this.code = code;
3471
- this.name = "ManagementError";
3472
- this.statusCode = options?.statusCode;
3574
+ // src/contract/management-keys/parse-user-memberships/parse-user-memberships.ts
3575
+ var parseUserMemberships = (value) => {
3576
+ if (!isRecord(value)) {
3577
+ throw new ContractParseError("invalid user memberships");
3473
3578
  }
3474
- code;
3475
- statusCode;
3579
+ const rows = value["org_memberships"];
3580
+ if (!Array.isArray(rows)) {
3581
+ throw new ContractParseError("invalid user memberships");
3582
+ }
3583
+ return {
3584
+ org_memberships: rows.map((row) => {
3585
+ if (!isRecord(row)) {
3586
+ throw new ContractParseError("invalid user memberships");
3587
+ }
3588
+ const orgId = row["org_id"];
3589
+ const orgName = row["org_name"];
3590
+ if (typeof orgId !== "string" || typeof orgName !== "string") {
3591
+ throw new ContractParseError("invalid user memberships");
3592
+ }
3593
+ return { org_id: orgId, org_name: orgName };
3594
+ })
3595
+ };
3476
3596
  };
3477
3597
 
3478
3598
  // src/management/sdk-management-keys/sdk-management-keys.ts
@@ -3571,26 +3691,42 @@ var sdkManagementKeys = (options) => {
3571
3691
  await call(accessToken, (client) => client.GET("/api/v1/orgs", {})),
3572
3692
  parseOrganization
3573
3693
  ),
3694
+ listMemberships: async (accessToken, userId) => parseUserMemberships(
3695
+ await call(
3696
+ accessToken,
3697
+ (client) => client.GET("/api/v1/users/{user_id}/memberships", {
3698
+ params: { path: { user_id: userId } }
3699
+ })
3700
+ )
3701
+ ),
3702
+ listProjectBudgets: async (accessToken, userId) => parseCollection(
3703
+ await call(
3704
+ accessToken,
3705
+ (client) => client.GET("/api/v1/users/{user_id}/project-budgets", {
3706
+ params: { path: { user_id: userId } }
3707
+ })
3708
+ ),
3709
+ parseProjectBudgetState
3710
+ ),
3574
3711
  listProjects: async (accessToken, organisationId) => {
3575
3712
  if (organisationId.trim().length === 0) {
3576
3713
  throw new ManagementError("MANAGEMENT_ORGANISATION_ID_REQUIRED", {
3577
3714
  statusCode: 400
3578
3715
  });
3579
3716
  }
3580
- return parseCollection(
3581
- await call(
3582
- accessToken,
3583
- (client) => client.GET("/api/v1/projects", {
3584
- params: {
3585
- query: {
3586
- member_user_id: parseManagementSubject(accessToken),
3587
- org_id: organisationId
3588
- }
3589
- }
3590
- })
3591
- ),
3592
- parseProject
3593
- );
3717
+ const query = {
3718
+ member_user_id: parseManagementSubject(accessToken),
3719
+ org_id: organisationId
3720
+ };
3721
+ const fetchPage = (cursor) => call(
3722
+ accessToken,
3723
+ (client) => client.GET("/api/v1/projects", {
3724
+ params: {
3725
+ query: cursor === "" ? query : { ...query, cursor }
3726
+ }
3727
+ })
3728
+ ).then((page) => parseCollection(page, parseProject));
3729
+ return drainPages(fetchPage);
3594
3730
  },
3595
3731
  regenerate: async (accessToken, id, expiresAt) => parseKeyMaterial(
3596
3732
  await call(
@@ -3949,7 +4085,6 @@ var bootstrapProvider = async (deps, sink) => {
3949
4085
  try {
3950
4086
  await runtime2.login({ allowBrowser: false });
3951
4087
  } catch {
3952
- return;
3953
4088
  }
3954
4089
  await deps.registerProjectForm().catch(() => void 0);
3955
4090
  try {
@@ -4070,39 +4205,34 @@ var createConnectAuthorize = (deps) => async (answer = {}) => {
4070
4205
  if (detectWorktreeRoot(deps.directory) === void 0) {
4071
4206
  throw new GatewayCredentialError(CONNECT_COPY.failFastWorktree);
4072
4207
  }
4073
- await applyWizardAnswer(deps, answer);
4074
- if (readAttribution(deps.state) !== void 0) {
4075
- const callback2 = deps.resolveCredential();
4076
- const decision2 = await deps.stash.urlForConnect(
4077
- callback2.then(() => void 0)
4078
- );
4079
- return {
4080
- callback: callback2,
4081
- instructions: decision2.instructions,
4082
- mode: "auto",
4083
- url: decision2.url
4084
- };
4085
- }
4086
- const runtime2 = deps.getRuntime();
4087
- if (runtime2 === void 0) {
4088
- throw new GatewayCredentialError(
4089
- "Route 33 authorization is unavailable in this host"
4090
- );
4091
- }
4092
4208
  const callback = (async () => {
4093
- await runtime2.login();
4094
- try {
4095
- return await deps.resolveCredential();
4096
- } catch (error) {
4097
- if (error instanceof AttributionPromptError && error.code === "ATTRIBUTION_PRESENTER_UNAVAILABLE") {
4098
- await deps.registerProjectForm();
4099
- throw new GatewayCredentialError(CONNECT_COPY.signedInNextStep);
4209
+ const emptyAnswer = Object.keys(answer).length === 0;
4210
+ if (emptyAnswer && readAttribution(deps.state) === void 0) {
4211
+ const runtime2 = deps.getRuntime();
4212
+ if (runtime2 === void 0) {
4213
+ throw new GatewayCredentialError(
4214
+ "Route 33 authorization is unavailable in this host"
4215
+ );
4100
4216
  }
4101
- throw error;
4217
+ await runtime2.login({ allowBrowser: false });
4218
+ try {
4219
+ return await deps.resolveCredential();
4220
+ } catch (error) {
4221
+ if (error instanceof AttributionPromptError && error.code === "ATTRIBUTION_PRESENTER_UNAVAILABLE") {
4222
+ await deps.registerProjectForm();
4223
+ throw new GatewayCredentialError(CONNECT_COPY.signedInNextStep);
4224
+ }
4225
+ throw error;
4226
+ }
4227
+ }
4228
+ await applyWizardAnswer(deps, answer);
4229
+ if (readAttribution(deps.state) === void 0) {
4230
+ throw new GatewayCredentialError(CONNECT_COPY.selectionInvalid);
4102
4231
  }
4232
+ return deps.resolveCredential();
4103
4233
  })();
4104
4234
  const decision = await deps.stash.urlForConnect(
4105
- callback.catch(() => void 0)
4235
+ callback.then(() => void 0)
4106
4236
  );
4107
4237
  return {
4108
4238
  callback,
@@ -4214,20 +4344,29 @@ var hostLeaseStateStore = (options) => ({
4214
4344
  });
4215
4345
 
4216
4346
  // src/v2-entry/host-token-store/host-token-store.ts
4217
- var DEFAULT_TOKEN_KEY = "route33:auth";
4218
- var hostTokenStore = (options) => ({
4219
- get: async () => {
4220
- const value = await options.storage.get(options.key ?? DEFAULT_TOKEN_KEY);
4221
- return typeof value === "string" ? value : void 0;
4222
- },
4223
- set: async (value) => {
4224
- if (value === void 0) {
4225
- await options.storage.remove(options.key ?? DEFAULT_TOKEN_KEY);
4226
- return;
4347
+ var DEFAULT_TOKEN_KEY = "route33_auth";
4348
+ var LEGACY_TOKEN_KEY = "route33:auth";
4349
+ var hostTokenStore = (options) => {
4350
+ const key = options.key ?? DEFAULT_TOKEN_KEY;
4351
+ return {
4352
+ get: async () => {
4353
+ const value = await options.storage.get(key);
4354
+ if (typeof value === "string") {
4355
+ return value;
4356
+ }
4357
+ const legacy = await options.storage.get(LEGACY_TOKEN_KEY);
4358
+ return typeof legacy === "string" ? legacy : void 0;
4359
+ },
4360
+ set: async (value) => {
4361
+ if (value === void 0) {
4362
+ await options.storage.remove(key);
4363
+ } else {
4364
+ await options.storage.set(key, value);
4365
+ }
4366
+ await options.storage.remove(LEGACY_TOKEN_KEY);
4227
4367
  }
4228
- await options.storage.set(options.key ?? DEFAULT_TOKEN_KEY, value);
4229
- }
4230
- });
4368
+ };
4369
+ };
4231
4370
 
4232
4371
  // src/v2-entry/mint-and-refresh/mint-and-refresh.ts
4233
4372
  var mintAndRefresh = async (deps, attribution, extras) => {
@@ -4236,66 +4375,6 @@ var mintAndRefresh = async (deps, attribution, extras) => {
4236
4375
  return minted;
4237
4376
  };
4238
4377
 
4239
- // src/v2-entry/format-inspect-reply/format-inspect-reply.ts
4240
- var formatInspectReply = (inspection) => {
4241
- const lines = [];
4242
- if (inspection.attribution === void 0) {
4243
- return "Route 33 is not connected in this folder \u2014 run /connect or /r33 to set a budget.";
4244
- }
4245
- lines.push(
4246
- inspection.attribution.kind === "personal" ? "Budget: Personal" : `Budget: Project ${inspection.attribution.projectId}`
4247
- );
4248
- if (inspection.key !== void 0) {
4249
- const scope = inspection.key.projectName === null ? "your personal budget" : `${inspection.key.organisationName ?? "unknown organisation"} \xB7 ${inspection.key.projectName}`;
4250
- lines.push(`Key: ${inspection.key.name} on ${scope}`);
4251
- }
4252
- if (inspection.lease !== void 0) {
4253
- lines.push(`Expires: ${inspection.lease.expiresAt}`);
4254
- lines.push(`Key id: ${inspection.lease.keyId}`);
4255
- }
4256
- return lines.join("\n");
4257
- };
4258
-
4259
- // src/v2-entry/parse-r33-subcommand/parse-r33-subcommand.ts
4260
- var SUBCOMMANDS = ["inspect", "logout", "rotate", "reset"];
4261
- var parseR33Subcommand = (promptText) => {
4262
- const [first = "", ...rest] = promptText.trim().split(/\s+/u).filter(Boolean);
4263
- const name = first.replace(/^\/+/u, "").split(":")[0] ?? "";
4264
- const argument = name === "r33" ? rest[0] : first;
4265
- if (argument === void 0 || argument === "") {
4266
- return "inspect";
4267
- }
4268
- return SUBCOMMANDS.includes(argument) ? argument : "help";
4269
- };
4270
-
4271
- // src/v2-entry/r33-command/r33-command.ts
4272
- var executeR33Command = async (input) => {
4273
- const subcommand = parseR33Subcommand(input.promptText);
4274
- if (input.handlers === void 0) {
4275
- return "Route 33 is not connected in this folder. Run /connect, choose Route 33, and follow the steps.";
4276
- }
4277
- if (subcommand === "help") {
4278
- return "Route 33 usage: /r33 [inspect|rotate|reset|logout] \u2014 inspect shows attribution and key rotation, rotate rotates the key now, reset clears the assigned budget (assign again with /connect).";
4279
- }
4280
- switch (subcommand) {
4281
- case "rotate": {
4282
- const lease = await input.handlers["rotate-now"]();
4283
- return `Route 33 key rotated. Key ${lease.keyId} is valid until ${lease.expiresAt}.`;
4284
- }
4285
- case "logout": {
4286
- await input.handlers["logout"]();
4287
- return "Logged out of Route 33 \u2014 the next OpenCode start signs in again.";
4288
- }
4289
- case "reset": {
4290
- await input.handlers["reset-attribution"]();
4291
- return "Route 33 attribution cleared. Run /connect, choose Route 33, and assign a budget again.";
4292
- }
4293
- default: {
4294
- return formatInspectReply(await input.handlers["inspect-session"]());
4295
- }
4296
- }
4297
- };
4298
-
4299
4378
  // src/v2-entry/model-gate-notify-from/model-gate-notify-from.ts
4300
4379
  var notifyFrom = async (session, sessionID, message) => {
4301
4380
  await session.synthetic?.({ delivery: "queue", sessionID, text: message });
@@ -4389,7 +4468,7 @@ var registerRoute33ModelGate = async (deps) => deps.session.hook(
4389
4468
  );
4390
4469
 
4391
4470
  // src/v2-entry/resolve-host-credential/resolve-host-credential.ts
4392
- var NO_USABLE_LEASE_MESSAGE = "Route 33 authorization completed without a usable gateway lease";
4471
+ var NO_USABLE_LEASE_MESSAGE = "Signed in to Route 33 \u2713. One more step: this folder has no gateway key yet \u2014 pick its budget to finish setup.";
4393
4472
  var resolveHostCredential = async (deps) => {
4394
4473
  await deps.config();
4395
4474
  deps.onProvider(deps.parseProvider(void 0));
@@ -4443,11 +4522,11 @@ var createRoute33V2Plugin = (options = {}) => {
4443
4522
  };
4444
4523
  const installation = createLeaseInstallationFactory({
4445
4524
  createSecretStore: (scopeId) => new HostStorageSecretStore({
4446
- key: `route33:lease:${scopeId}`,
4525
+ key: `route33_lease_${scopeId}`,
4447
4526
  storage: context.storage
4448
4527
  }),
4449
4528
  createStateStore: (scopeId) => hostLeaseStateStore({
4450
- key: `route33:lease:${scopeId}:state`,
4529
+ key: `route33_lease_${scopeId}_state`,
4451
4530
  storage: context.storage
4452
4531
  })
4453
4532
  });
@@ -4493,7 +4572,7 @@ var createRoute33V2Plugin = (options = {}) => {
4493
4572
  return;
4494
4573
  }
4495
4574
  const [projects, modelIds, personalKeyActive] = await Promise.all([
4496
- activeRuntime.listProjects(),
4575
+ activeRuntime.listMintableProjects({ allowBrowser: false }).catch(() => []),
4497
4576
  activeRuntime.catalogModelIds(),
4498
4577
  activeRuntime.hasPersonalLease().catch(() => false)
4499
4578
  ]);
@@ -4547,23 +4626,6 @@ var createRoute33V2Plugin = (options = {}) => {
4547
4626
  });
4548
4627
  }
4549
4628
  );
4550
- const commandTransform = await context.command.transform((editor) => {
4551
- editor.add({
4552
- description: "Route 33 actions: /r33 [inspect|rotate|reset|logout] \u2014 inspect shows attribution and key details, rotate rotates the key now, reset clears the assigned budget, logout signs out of Route 33",
4553
- execute: async ({ prompt, sessionID }) => {
4554
- const text = await executeR33Command({
4555
- handlers: runtime2?.commandHandlers(),
4556
- promptText: prompt.text
4557
- });
4558
- await context.session.synthetic({
4559
- delivery: "queue",
4560
- sessionID,
4561
- text
4562
- });
4563
- },
4564
- name: "r33"
4565
- });
4566
- });
4567
4629
  const sessionHook = await context.session.hook(
4568
4630
  "http.request",
4569
4631
  createWorkspaceKeyHook({
@@ -4597,7 +4659,6 @@ var createRoute33V2Plugin = (options = {}) => {
4597
4659
  ]);
4598
4660
  return async () => {
4599
4661
  await Promise.all([
4600
- commandTransform.dispose(),
4601
4662
  integrationTransform.dispose(),
4602
4663
  providerTransform.dispose(),
4603
4664
  sessionHook.dispose(),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@r-33/opencode",
3
- "version": "0.4.7-rc.23",
3
+ "version": "0.4.7-rc.25",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -34,8 +34,8 @@
34
34
  }
35
35
  },
36
36
  "dependencies": {
37
- "@r-33/sdk": "0.1.1-rc.3",
38
- "@r-33/auth-browser": "0.1.1-rc.2"
37
+ "@r-33/auth-browser": "0.1.1-rc.3",
38
+ "@r-33/sdk": "0.1.1-rc.4"
39
39
  },
40
40
  "devDependencies": {
41
41
  "@opencode-ai/plugin": "^1.18.0",