@the-vibe-company/armada 0.1.17 → 0.1.18

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.
Files changed (2) hide show
  1. package/dist/armada.js +262 -42
  2. package/package.json +1 -1
package/dist/armada.js CHANGED
@@ -346,7 +346,7 @@ function armadaApi(opts) {
346
346
  const headers = { Accept: "application/json" };
347
347
  if (init.body)
348
348
  headers["Content-Type"] = "application/json";
349
- if (init.signIn?.kind === "session")
349
+ if (init.signIn?.kind === "session" || init.signIn?.kind === "worker")
350
350
  headers.Authorization = `Bearer ${init.signIn.token}`;
351
351
  if (init.signIn?.kind === "api-key")
352
352
  headers["x-api-key"] = init.signIn.key;
@@ -409,8 +409,11 @@ function armadaApi(opts) {
409
409
  throw refusal(status, body, status === 401 ? null : "Armada could not say who is signed in");
410
410
  return body;
411
411
  },
412
- async credentials(signIn, held) {
413
- const { status, body } = await call("POST", "credentials", { signIn, body: { turso: held } });
412
+ async credentials(signIn, held, purpose = null) {
413
+ const { status, body } = await call("POST", "credentials", {
414
+ signIn,
415
+ body: purpose ? { turso: held, purpose } : { turso: held }
416
+ });
414
417
  if (status !== 200)
415
418
  throw refusal(status, body, status === 401 ? null : "Armada gave no keys");
416
419
  const str = (v) => typeof v === "string" && v.length > 0;
@@ -423,6 +426,31 @@ function armadaApi(opts) {
423
426
  const warnings = Array.isArray(body.warnings) ? body.warnings.filter((w) => typeof w === "string") : [];
424
427
  return { ...body, warnings };
425
428
  },
429
+ async launchToken(signIn, target) {
430
+ const { status, body } = await call("POST", "launch-tokens", { signIn, body: target });
431
+ if (status !== 200)
432
+ throw refusal(status, body, status === 401 ? null : "Armada made no launch token");
433
+ const w = body.worker;
434
+ if (typeof body.token !== "string" || typeof body.expiresAt !== "string" || !w?.ticket)
435
+ throw new ArmadaApiError(`Armada (${host}) answered the launch token in a shape this CLI does not know`);
436
+ return body;
437
+ },
438
+ async exchangeLaunchToken(token) {
439
+ const { status, body } = await call("POST", "launch-tokens/exchange", { body: { token } });
440
+ if (status !== 200)
441
+ throw refusal(status, body, null);
442
+ const w = body.worker;
443
+ const org = body.organization;
444
+ if (typeof body.token !== "string" || !w?.ticket || !w.project || !org?.id)
445
+ throw new ArmadaApiError(`Armada (${host}) answered the launch token in a shape this CLI does not know`);
446
+ return body;
447
+ },
448
+ async endWorkers(signIn, target) {
449
+ const { status, body } = await call("POST", "workers/end", { signIn, body: target });
450
+ if (status !== 200)
451
+ throw refusal(status, body, "Armada did not end the ticket's workers");
452
+ return typeof body.ended === "number" ? body.ended : 0;
453
+ },
426
454
  async signOut(signIn) {
427
455
  const { status, body } = await call("DELETE", "session", { signIn });
428
456
  if (status !== 200)
@@ -3174,9 +3202,11 @@ function buildBrief(input) {
3174
3202
  choice?.reason ? ` --reason ${shellWord(choice.reason)}` : ""
3175
3203
  ].join("");
3176
3204
  const has = (name) => !!input.env[name]?.trim();
3205
+ const launch = input.launch ?? null;
3177
3206
  const environment = [
3178
3207
  ...VARIABLES.map((v) => ({
3179
3208
  ...v,
3209
+ ...launch ? { required: false, purpose: `${v.purpose}; not needed: the launch token signs the worker in` } : {},
3180
3210
  value: null,
3181
3211
  inShell: has(v.name),
3182
3212
  inStore: !has(v.name) && !!input.stored?.includes(v.name)
@@ -3207,6 +3237,11 @@ function buildBrief(input) {
3207
3237
  install: `npm install -g ${pkg}`,
3208
3238
  fallback: `npm exec --yes --package=${pkg} -- armada`,
3209
3239
  claimCommand,
3240
+ launch: launch ? {
3241
+ command: `armada login --launch-token ${shellWord(launch.token)}${launch.apiUrl ? ` --api-url ${shellWord(launch.apiUrl)}` : ""}`,
3242
+ expiresAt: launch.expiresAt
3243
+ } : null,
3244
+ noLaunch: launch ? null : input.noLaunch ?? null,
3210
3245
  environment,
3211
3246
  blockers: ticket.blockers.map(({ notes, ...b }) => ({ ...b, handBack: handBackNote(notes) })),
3212
3247
  notes: ticket.notes.slice(0, MAX_NOTES),
@@ -3233,10 +3268,15 @@ function renderPrompt(b) {
3233
3268
  "",
3234
3269
  "```sh",
3235
3270
  b.install,
3271
+ ...b.launch ? [b.launch.command] : [],
3236
3272
  b.claimCommand,
3237
3273
  "```",
3238
3274
  "",
3239
3275
  `This installs the coordinator's Armada version. If the global install is refused, use \`${b.fallback}\` wherever this brief or the skill says \`armada\`.`,
3276
+ ...b.launch ? [
3277
+ "",
3278
+ `\`armada login --launch-token\` signs this workspace in to Armada as the worker of ${t.id}, with a one-time token valid until ${b.launch.expiresAt.slice(0, 16).replace("T", " ")} UTC. Run it first, once.`
3279
+ ] : [],
3240
3280
  "",
3241
3281
  "If the claim is refused, stop and quote the refusal in your reply (usually another worker holds the ticket).",
3242
3282
  "",
@@ -3270,7 +3310,7 @@ ${quote(x.handBack.body)}` : "No hand-back note.", "");
3270
3310
  out.push(`- ${w.id} — ${w.title} (${w.phase})${w.branch ? `, branch \`${w.branch}\`` : ""}${w.pr ? `, ${w.pr}` : ""}`);
3271
3311
  } else
3272
3312
  out.push("None.");
3273
- out.push("", "## Environment", "", `The coordinator set ${b.environment.map((v) => `\`${v.name}\``).join(", ")} in this workspace. Never print, commit or log their values.`);
3313
+ out.push("", "## Environment", "", b.launch ? `No key is needed in this workspace: once signed in, Armada hands each command the keys it needs, for ${t.id} only. If a command says this worker was cut off from Armada, stop and say so in your reply. Never print, commit or log a token or a key.` : `The coordinator set ${b.environment.map((v) => `\`${v.name}\``).join(", ")} in this workspace. Never print, commit or log their values.`);
3274
3314
  return `${out.join(`
3275
3315
  `)}
3276
3316
  `;
@@ -3291,6 +3331,12 @@ async function loadBrief(config, opts) {
3291
3331
  ]);
3292
3332
  if (!ticket)
3293
3333
  throw new Refusal(`ticket ${opts.ticket} not found in Linear`, "armada status, to see the tickets of the program");
3334
+ const open = ticket.statusType !== "completed" && ticket.statusType !== "canceled";
3335
+ const launch = open && opts.launch ? await opts.launch(ticket.id) : null;
3336
+ const made = launch && "token" in launch ? launch : null;
3337
+ const missed = launch && "reason" in launch ? launch : null;
3338
+ if (missed?.warn)
3339
+ ticket.warnings.push(`no launch token: ${missed.reason}`);
3294
3340
  return buildBrief({
3295
3341
  config,
3296
3342
  ticket,
@@ -3300,6 +3346,8 @@ async function loadBrief(config, opts) {
3300
3346
  version: opts.version,
3301
3347
  env: opts.env,
3302
3348
  ...opts.stored ? { stored: opts.stored } : {},
3349
+ launch: made,
3350
+ noLaunch: missed?.reason ?? null,
3303
3351
  now: now()
3304
3352
  });
3305
3353
  }
@@ -3310,22 +3358,38 @@ var API_KEY_VARIABLE = "ARMADA_API_KEY";
3310
3358
  var API_URL_VARIABLE = "ARMADA_API_URL";
3311
3359
  var SIGNED_IN_TO_VARIABLE = "ARMADA_SIGNED_IN_TO";
3312
3360
  var TURSO_LEASE_VARIABLE = "ARMADA_TURSO_LEASE";
3313
- var formatLease = (lease) => Buffer.from(JSON.stringify(lease), "utf8").toString("base64url");
3314
- function parseLease(value) {
3361
+ var WORKER_SESSION_PREFIX = "ARMADA_WORKER_SESSION_";
3362
+ var workerSessionVariable = (ticket) => `${WORKER_SESSION_PREFIX}${ticket.toUpperCase().replace(/[^A-Z0-9]/g, "_")}`;
3363
+ var formatRecord = (record) => Buffer.from(JSON.stringify(record), "utf8").toString("base64url");
3364
+ function parseRecord(value, keys) {
3315
3365
  if (!value?.trim())
3316
3366
  return null;
3317
3367
  try {
3318
- const l = JSON.parse(Buffer.from(value.trim(), "base64url").toString("utf8"));
3319
- const keys = ["api", "organization", "url", "token", "expiresAt", "revision"];
3320
- if (!keys.every((k) => typeof l[k] === "string" && l[k]))
3368
+ const r = JSON.parse(Buffer.from(value.trim(), "base64url").toString("utf8"));
3369
+ if (!keys.every((k) => typeof r[k] === "string" && r[k]))
3321
3370
  return null;
3322
- if (Number.isNaN(Date.parse(String(l.expiresAt))))
3323
- return null;
3324
- return Object.fromEntries(keys.map((k) => [k, String(l[k])]));
3371
+ return Object.fromEntries(keys.map((k) => [k, String(r[k])]));
3325
3372
  } catch {
3326
3373
  return null;
3327
3374
  }
3328
3375
  }
3376
+ var formatLease = (lease) => formatRecord(lease);
3377
+ function parseLease(value) {
3378
+ const l = parseRecord(value, ["api", "organization", "url", "token", "expiresAt", "revision"]);
3379
+ return l && !Number.isNaN(Date.parse(l.expiresAt)) ? l : null;
3380
+ }
3381
+ var formatWorkerSession = (worker) => formatRecord(worker);
3382
+ function parseWorkerSession(value) {
3383
+ return parseRecord(value, ["api", "token", "ticket", "project", "organization", "id"]);
3384
+ }
3385
+ function storedWorkers(store) {
3386
+ return Object.entries(store).flatMap(([variable, value]) => {
3387
+ if (!variable.startsWith(WORKER_SESSION_PREFIX))
3388
+ return [];
3389
+ const w = parseWorkerSession(value);
3390
+ return w && workerSessionVariable(w.ticket) === variable ? [w] : [];
3391
+ });
3392
+ }
3329
3393
  function armadaAddress(url) {
3330
3394
  try {
3331
3395
  const u = new URL(url.trim());
@@ -3363,7 +3427,14 @@ var fromEnv = (env, variable) => {
3363
3427
  const value = clean(env[variable]);
3364
3428
  return value ? { value, source: { kind: "env", variable } } : null;
3365
3429
  };
3366
- function resolveCredentials({ env, store = {}, personal, ghToken, armada }) {
3430
+ function resolveCredentials({
3431
+ env,
3432
+ store = {},
3433
+ personal,
3434
+ ghToken,
3435
+ armada,
3436
+ ticket
3437
+ }) {
3367
3438
  const fromStore = (variable) => {
3368
3439
  const value = clean(store[variable]);
3369
3440
  return value ? { value, source: { kind: "store" } } : null;
@@ -3376,14 +3447,23 @@ function resolveCredentials({ env, store = {}, personal, ghToken, armada }) {
3376
3447
  const tursoUrlConfig = clean(personal?.turso.url);
3377
3448
  const apiUrlConfig = clean(personal?.api.url);
3378
3449
  const apiUrl = fromEnv(env, API_URL_VARIABLE);
3379
- const armadaApi = apiUrl ? { url: apiUrl.value, source: apiUrl.source } : apiUrlConfig ? { url: apiUrlConfig, source: { kind: "config", key: "api.url" } } : { url: DEFAULT_ARMADA_API_URL, source: { kind: "default" } };
3450
+ const workers = storedWorkers(store);
3451
+ const worker = ticket ? workers.find((w) => w.ticket === ticket.toUpperCase()) : undefined;
3452
+ const armadaApi = apiUrl ? { url: apiUrl.value, source: apiUrl.source } : apiUrlConfig ? { url: apiUrlConfig, source: { kind: "config", key: "api.url" } } : worker ? { url: worker.api, source: { kind: "store" } } : { url: DEFAULT_ARMADA_API_URL, source: { kind: "default" } };
3453
+ const workerHere = worker && armadaAddress(worker.api) === armadaAddress(armadaApi.url) ? worker : null;
3380
3454
  const envKey = fromEnv(env, API_KEY_VARIABLE);
3381
3455
  const signedInTo = armadaAddress(clean(store[SIGNED_IN_TO_VARIABLE]) ?? DEFAULT_ARMADA_API_URL);
3382
3456
  const here = signedInTo === armadaAddress(armadaApi.url);
3383
3457
  const session = fromStore(SESSION_TOKEN_VARIABLE);
3384
3458
  const storedKey = fromStore(API_KEY_VARIABLE);
3385
3459
  const armadaSignInElsewhere = !here && (session || storedKey) ? signedInTo : null;
3386
- const armadaSignIn = envKey ? { kind: "api-key", key: envKey.value, source: envKey.source } : session && here ? { kind: "session", token: session.value, source: session.source } : storedKey && here ? { kind: "api-key", key: storedKey.value, source: storedKey.source } : null;
3460
+ const armadaSignIn = workerHere ? {
3461
+ kind: "worker",
3462
+ token: workerHere.token,
3463
+ ticket: workerHere.ticket,
3464
+ project: workerHere.project,
3465
+ source: { kind: "store" }
3466
+ } : envKey ? { kind: "api-key", key: envKey.value, source: envKey.source } : session && here ? { kind: "session", token: session.value, source: session.source } : storedKey && here ? { kind: "api-key", key: storedKey.value, source: storedKey.source } : null;
3387
3467
  const fromArmada = (value, detail) => value && detail ? { value, source: { kind: "armada", detail } } : null;
3388
3468
  const tursoPair = armada?.turso && !fromEnv(env, "ARMADA_TURSO_URL") && !fromEnv(env, "ARMADA_TURSO_TOKEN") ? armada.turso : null;
3389
3469
  const found = {
@@ -3405,7 +3485,8 @@ function resolveCredentials({ env, store = {}, personal, ghToken, armada }) {
3405
3485
  },
3406
3486
  armadaApi,
3407
3487
  armadaSignIn,
3408
- armadaSignInElsewhere: envKey ? null : armadaSignInElsewhere
3488
+ workerTickets: workers.map((w) => w.ticket),
3489
+ armadaSignInElsewhere: envKey || workerHere ? null : armadaSignInElsewhere
3409
3490
  };
3410
3491
  }
3411
3492
  var missingKeys = (credentials) => STORED_KEYS.filter((k) => credentials[k.name] === null);
@@ -4942,7 +5023,7 @@ You are a worker. You own exactly one ticket, named in your launch brief. You tu
4942
5023
 
4943
5024
  ## Steps
4944
5025
 
4945
- 1. **Claim** with the exact command your brief starts with, for example \`armada claim <ticket> --runtime conductor --handle "$CONDUCTOR_WORKSPACE_ID/$CONDUCTOR_SESSION_ID"\`. Install the Armada version the brief names first; if it gives a fallback command, use it wherever this skill says \`armada\`. It assigns the ticket, moves it to In Progress, sets \`Agent phase = planning\` and your \`Agent runtime\`, and posts the \`Agent claim\` comment. If it refuses because another claim exists, stop: the older claim wins.
5026
+ 1. **Claim** with the exact commands your brief starts with, for example \`armada claim <ticket> --runtime conductor --handle "$CONDUCTOR_WORKSPACE_ID/$CONDUCTOR_SESSION_ID"\`. Install the Armada version the brief names first; if it gives a fallback command, use it wherever this skill says \`armada\`. When the brief has an \`armada login --launch-token <token>\` line, run it once, before the claim: it signs your workspace in to Armada for your ticket only, and Armada then gives each command its keys, so none is needed in your environment. The token works once, within the hour; if it is refused, or a later command says you were cut off from Armada, stop and say so in your reply. The claim assigns the ticket, moves it to In Progress, sets \`Agent phase = planning\` and your \`Agent runtime\`, and posts the \`Agent claim\` comment. If it refuses because another claim exists, stop: the older claim wins.
4946
5027
  2. **Branch.** Use the branch named after the ticket (the tracker suggests one, for example \`feature/abc-12-short-title\`), created from the latest default branch.
4947
5028
  3. **Plan.** Write the plan: what changes, how it is tested, and the checks a person could observe when it is done. If the ticket's plan policy or your brief says plans are pre-approved, post the full plan with \`armada report implementing --message "<plan>"\` and go on; do not enter \`awaiting-approval\`. Otherwise post the full plan with \`armada report awaiting-approval --message "<plan>"\`: it creates a \`plan\` item in the coordinator's inbox. Push your branch and wait for the coordinator's decision in your session. On approval, report \`implementing\`; on amendments, report \`planning\`, revise the plan and submit it for approval again.
4948
5029
  4. **Implement** test-first. A material change to the approved plan needs a new approval.
@@ -5325,7 +5406,7 @@ async function loadStatus(config, opts) {
5325
5406
  });
5326
5407
  }
5327
5408
  // package.json
5328
- var version = "0.1.17";
5409
+ var version = "0.1.18";
5329
5410
 
5330
5411
  // src/io.ts
5331
5412
  class UsageError extends Error {
@@ -5355,7 +5436,7 @@ var fromLease = (lease) => ({
5355
5436
  token: lease.token,
5356
5437
  detail: `a token made for this terminal, expires ${hhmm(lease.expiresAt)}`
5357
5438
  });
5358
- async function fromArmada(io, machine, credentials) {
5439
+ async function fromArmada(io, machine, credentials, purpose) {
5359
5440
  const signIn = credentials.armadaSignIn;
5360
5441
  if (!signIn)
5361
5442
  return null;
@@ -5371,12 +5452,14 @@ async function fromArmada(io, machine, credentials) {
5371
5452
  };
5372
5453
  let answer;
5373
5454
  try {
5374
- answer = await armadaApi({ url: credentials.armadaApi.url, ...io.fetch ? { fetch: io.fetch } : {} }).credentials(signIn, lease ? { revision: lease.revision, expiresAt: lease.expiresAt } : null);
5455
+ answer = await armadaApi({ url: credentials.armadaApi.url, ...io.fetch ? { fetch: io.fetch } : {} }).credentials(signIn, lease ? { revision: lease.revision, expiresAt: lease.expiresAt } : null, purpose);
5375
5456
  } catch (err) {
5376
5457
  if (!(err instanceof ArmadaApiError))
5377
5458
  throw err;
5378
5459
  if (err.signedOut || err.status === 403) {
5379
5460
  await keep(null);
5461
+ if (signIn.kind === "worker")
5462
+ throw err;
5380
5463
  io.stderr(`! Armada gave no keys (${err.message}); using this machine's${err.next ? `. Next: ${err.next}` : ""}
5381
5464
  `);
5382
5465
  return null;
@@ -5415,8 +5498,15 @@ async function fromArmada(io, machine, credentials) {
5415
5498
  turso: t?.kind === "stored" ? { url: t.url, token: t.token, detail: `the stored Turso access of ${answer.organization.name}` } : null
5416
5499
  };
5417
5500
  }
5418
- async function loadCredentials(io, { armada = true } = {}) {
5501
+ async function loadCredentials(io, { armada = true, worker } = {}) {
5419
5502
  const machine = await loadMachine(io);
5503
+ let ticket = null;
5504
+ if (worker)
5505
+ try {
5506
+ ticket = worker.ticket(storedWorkers(machine.store?.values ?? {}).map((w) => w.ticket));
5507
+ } catch {
5508
+ ticket = null;
5509
+ }
5420
5510
  let gh;
5421
5511
  const sources = {
5422
5512
  env: io.env,
@@ -5426,12 +5516,21 @@ async function loadCredentials(io, { armada = true } = {}) {
5426
5516
  return gh;
5427
5517
  },
5428
5518
  ...machine.store ? { store: machine.store.values } : {},
5429
- ...machine.personal ? { personal: machine.personal.config } : {}
5519
+ ...machine.personal ? { personal: machine.personal.config } : {},
5520
+ ticket
5430
5521
  };
5431
5522
  const local = resolveCredentials(sources);
5432
- if (!armada || !local.armadaSignIn || !wantsArmada(io.env))
5523
+ const signIn = local.armadaSignIn;
5524
+ const purpose = worker && ticket ? { command: worker.command, project: worker.project, ticket } : null;
5525
+ if (signIn?.kind === "worker" && armada) {
5526
+ if (signIn.project !== worker?.project)
5527
+ throw new UsageError(`the worker session of ${signIn.ticket} is for the project ${signIn.project}, not ${worker?.project} (armada.toml): this repository is not its own`, `cd into the repository of ${signIn.project}`);
5528
+ const keys = await fromArmada(io, machine, local, purpose);
5529
+ return { machine, credentials: keys ? resolveCredentials({ ...sources, armada: keys }) : local };
5530
+ }
5531
+ if (!armada || !signIn || !wantsArmada(io.env))
5433
5532
  return { machine, credentials: local };
5434
- const keys = await fromArmada(io, machine, local);
5533
+ const keys = await fromArmada(io, machine, local, purpose);
5435
5534
  return { machine, credentials: keys ? resolveCredentials({ ...sources, armada: keys }) : local };
5436
5535
  }
5437
5536
  var describeSource = (s) => {
@@ -5535,8 +5634,9 @@ function buildAuthStatus(machine, credentials) {
5535
5634
  personalConfig: machine.paths && machine.personal ? { path: machine.paths.config, exists: machine.personal.exists } : null,
5536
5635
  signIn: {
5537
5636
  api: credentials.armadaApi,
5538
- method: credentials.armadaSignIn?.kind ?? null,
5539
- source: credentials.armadaSignIn?.source ?? null
5637
+ method: credentials.armadaSignIn?.kind === "worker" ? null : credentials.armadaSignIn?.kind ?? null,
5638
+ source: credentials.armadaSignIn?.kind === "worker" ? null : credentials.armadaSignIn?.source ?? null,
5639
+ workers: credentials.workerTickets
5540
5640
  },
5541
5641
  warnings: storeWarnings(machine)
5542
5642
  };
@@ -5559,6 +5659,8 @@ function renderAuthStatus(status) {
5559
5659
  const api = signIn.api.source.kind === "default" ? "built in" : describeSource(signIn.api.source);
5560
5660
  lines.push("", "Armada sign-in", ` API ${signIn.api.url} (${api})`);
5561
5661
  lines.push(signIn.method && signIn.source ? ` Signed in with ${signIn.method === "session" ? "the session of `armada login`" : "an organization API key"}, from the ${describeSource(signIn.source)}; \`armada whoami\` shows who` : " Signed in no: run `armada login`, or set ARMADA_API_KEY on a headless coordinator");
5662
+ if (signIn.workers.length)
5663
+ lines.push(` Workers ${signIn.workers.join(", ")}: the worker session of \`armada login --launch-token\` signs in that ticket's claim, report, ask and release`);
5562
5664
  return `${lines.join(`
5563
5665
  `)}
5564
5666
  `;
@@ -5603,6 +5705,7 @@ function renderBrief(b) {
5603
5705
  ...b.routing ? [`Chosen by: ${b.routing.why}`] : [],
5604
5706
  `Repository: ${b.repository.url}`,
5605
5707
  `Branch: ${b.ticket.branch ?? "none suggested by Linear"} (the worker renames its workspace branch to it)`,
5708
+ `Launch: ${b.launch ? `one-time token in the prompt, valid until ${b.launch.expiresAt.slice(0, 16).replace("T", " ")} UTC: the worker needs no key` : `no launch token${b.noLaunch ? ` (${b.noLaunch})` : ""}: pass the keys below in the worker's environment`}`,
5606
5709
  "",
5607
5710
  "Environment to pass (values are never printed):",
5608
5711
  ...b.environment.map((v) => {
@@ -5617,6 +5720,29 @@ function renderBrief(b) {
5617
5720
  return out.join(`
5618
5721
  `);
5619
5722
  }
5723
+ function launcher(io, config, credentials) {
5724
+ return async (ticket) => {
5725
+ const signIn = credentials.armadaSignIn;
5726
+ if (!signIn)
5727
+ return {
5728
+ reason: "launch tokens need this terminal signed in to an Armada with accounts: armada login",
5729
+ warn: false
5730
+ };
5731
+ const url = credentials.armadaApi.url;
5732
+ try {
5733
+ const t = await armadaApi({ url, ...io.fetch ? { fetch: io.fetch } : {} }).launchToken(signIn, {
5734
+ project: config.project.slug,
5735
+ ticket
5736
+ });
5737
+ const builtIn = armadaAddress(url) === armadaAddress(DEFAULT_ARMADA_API_URL);
5738
+ return { token: t.token, expiresAt: t.expiresAt, apiUrl: builtIn ? null : armadaAddress(url) };
5739
+ } catch (err) {
5740
+ if (!(err instanceof ArmadaApiError))
5741
+ throw err;
5742
+ return { reason: err.message, warn: true };
5743
+ }
5744
+ };
5745
+ }
5620
5746
  async function brief2(io, config, credentials, a, version) {
5621
5747
  const [ticket, ...extra] = a.rest;
5622
5748
  if (!ticket)
@@ -5649,6 +5775,7 @@ async function brief2(io, config, credentials, a, version) {
5649
5775
  version,
5650
5776
  env: io.env,
5651
5777
  stored: STORED_KEYS.filter((k) => credentials.sources[k.name]?.kind === "store").map((k) => k.variable),
5778
+ launch: launcher(io, config, credentials),
5652
5779
  ...io.fetch ? { fetch: io.fetch } : {},
5653
5780
  ...io.now ? { now: io.now } : {}
5654
5781
  });
@@ -5877,12 +6004,12 @@ function statusEvents(config, credentials) {
5877
6004
  }
5878
6005
  };
5879
6006
  }
5880
- function currentTicket(io, config, explicit) {
6007
+ function currentTicket(io, config, explicit, workers = []) {
5881
6008
  const fromEnv = io.env.ARMADA_TICKET?.trim();
5882
6009
  const id = explicit?.trim() || fromEnv || (() => {
5883
6010
  const branch = io.gitBranch?.();
5884
6011
  return branch ? ticketFromBranch(branch, config.tracker.programRoot) : null;
5885
- })();
6012
+ })() || (workers.length === 1 ? workers[0] : null);
5886
6013
  if (!id)
5887
6014
  throw new UsageError("which ticket? pass --ticket <id>, set ARMADA_TICKET, or run on the ticket's branch");
5888
6015
  return id.toUpperCase();
@@ -6010,7 +6137,7 @@ async function report(io, config, credentials, a) {
6010
6137
  const message = await readMessage(io, a.options);
6011
6138
  if (!message?.trim() && phase !== "ready-to-merge")
6012
6139
  throw new UsageError("--message is required: what you did or what you are doing (first line = summary)");
6013
- const ticket = currentTicket(io, config, a.options.ticket);
6140
+ const ticket = currentTicket(io, config, a.options.ticket, credentials.workerTickets);
6014
6141
  return withContext(io, config, credentials, a.json, (ctx) => reportPhase(ctx, {
6015
6142
  ticket,
6016
6143
  phase,
@@ -6025,8 +6152,35 @@ async function release(io, config, credentials, a) {
6025
6152
  const reason = a.options.reason?.trim();
6026
6153
  if (!reason)
6027
6154
  throw new UsageError("--reason is required: why the ticket is given back");
6028
- const ticket = currentTicket(io, config, a.options.ticket);
6029
- return withContext(io, config, credentials, a.json, (ctx) => releaseTicket(ctx, { ticket, reason }));
6155
+ const ticket = currentTicket(io, config, a.options.ticket, credentials.workerTickets);
6156
+ const code = await withContext(io, config, credentials, a.json, (ctx) => releaseTicket(ctx, { ticket, reason }));
6157
+ await endWorkerSessions(io, config, credentials, ticket, "released", a.json);
6158
+ return code;
6159
+ }
6160
+ async function endWorkerSessions(io, config, credentials, ticket, reason, quiet) {
6161
+ const signIn = credentials.armadaSignIn;
6162
+ if (!signIn)
6163
+ return;
6164
+ const api = armadaApi({ url: credentials.armadaApi.url, ...io.fetch ? { fetch: io.fetch } : {} });
6165
+ try {
6166
+ if (signIn.kind === "worker") {
6167
+ const paths = machinePaths(io.env);
6168
+ if (paths)
6169
+ await updateCredentialStore(paths, { [workerSessionVariable(signIn.ticket)]: null });
6170
+ await api.signOut(signIn);
6171
+ if (!quiet)
6172
+ io.stdout(`Signed out of Armada: the worker session of ${signIn.ticket} has ended.
6173
+ `);
6174
+ return;
6175
+ }
6176
+ const ended = await api.endWorkers(signIn, { project: config.project.slug, ticket, reason });
6177
+ if (ended && !quiet)
6178
+ io.stdout(`Ended ${ended === 1 ? "the worker session" : `${ended} worker sessions`} of ${ticket} on Armada.
6179
+ `);
6180
+ } catch (err) {
6181
+ io.stderr(`armada: warning: the worker session of ${ticket} was not ended on Armada (${err instanceof Error ? err.message : String(err)}); it ends on its own after 72 hours without a command, and the Workers page revokes it
6182
+ `);
6183
+ }
6030
6184
  }
6031
6185
 
6032
6186
  // src/inbox.ts
@@ -6042,7 +6196,7 @@ async function ask(io, config, credentials, a) {
6042
6196
  if (!question?.trim())
6043
6197
  throw new UsageError('ask needs a question: armada ask "<question, the options, your recommendation>"');
6044
6198
  const options = (a.options.options ?? "").split("|").map((o) => o.trim()).filter(Boolean);
6045
- const ticket = currentTicket(io, config, a.options.ticket);
6199
+ const ticket = currentTicket(io, config, a.options.ticket, credentials.workerTickets);
6046
6200
  return withContext(io, config, credentials, a.json, (ctx) => askCoordinator(ctx, { ticket, question, options }));
6047
6201
  }
6048
6202
  async function answer(io, config, credentials, a) {
@@ -6351,6 +6505,10 @@ function describeIdentity(identity) {
6351
6505
  const key = identity.apiKey?.name ?? identity.apiKey?.start ?? "an API key";
6352
6506
  return `the API key "${key}" of ${org}`;
6353
6507
  }
6508
+ if (identity.via === "worker") {
6509
+ const w = identity.worker;
6510
+ return w ? `the worker of ${w.ticket} (${w.project}), launched by ${w.launchedBy}, in ${org}` : `a worker of ${org}`;
6511
+ }
6354
6512
  const who = identity.user ? identity.user.name ? `${identity.user.name} <${identity.user.email}>` : identity.user.email : "?";
6355
6513
  return `${who}, ${org}`;
6356
6514
  }
@@ -6391,13 +6549,48 @@ The key is stored in ${p.credentials}.
6391
6549
  `);
6392
6550
  return 0;
6393
6551
  }
6394
- async function login(io, apiKey) {
6552
+ async function loginWithLaunchToken(io, credentials, token, apiUrl) {
6553
+ const p = paths(io);
6554
+ let url = credentials.armadaApi.url;
6555
+ if (apiUrl) {
6556
+ apiBaseUrl(apiUrl);
6557
+ if (credentials.armadaApi.source.kind !== "default" && armadaAddress(apiUrl) !== armadaAddress(url))
6558
+ throw new UsageError(`the launch message names ${hostOf(apiUrl)}, but ARMADA_API_URL or [api] url names ${hostOf(url)}`, "unset ARMADA_API_URL, or ask the coordinator for a launch from that Armada");
6559
+ url = apiUrl;
6560
+ }
6561
+ const session = await apiOf(io, url).exchangeLaunchToken(token.trim());
6562
+ const w = session.worker;
6563
+ await updateCredentialStore(p, {
6564
+ [workerSessionVariable(w.ticket)]: formatWorkerSession({
6565
+ api: armadaAddress(url),
6566
+ token: session.token,
6567
+ ticket: w.ticket,
6568
+ project: w.project,
6569
+ organization: session.organization.id,
6570
+ id: w.id
6571
+ })
6572
+ });
6573
+ io.stdout(`Signed in to ${hostOf(url)} as the worker of ${w.ticket} (${w.project}) in ${session.organization.name}, launched by ${w.launchedBy}.
6574
+ This terminal claims, reports, asks and releases ${w.ticket} only; Armada gives each of those commands its keys.
6575
+ `);
6576
+ return 0;
6577
+ }
6578
+ async function login(io, o) {
6579
+ if (o.apiUrl !== null && o.launchToken === null)
6580
+ throw new UsageError("--api-url goes with --launch-token: it names the Armada of the launch message");
6581
+ if (o.launchToken !== null && o.apiKey)
6582
+ throw new UsageError("pass --api-key or --launch-token, not both");
6395
6583
  const { machine, credentials } = await loadCredentials(io, { armada: false });
6584
+ if (o.launchToken !== null) {
6585
+ if (!o.launchToken.trim())
6586
+ throw new UsageError("--launch-token needs the token of the launch message");
6587
+ return loginWithLaunchToken(io, credentials, o.launchToken, o.apiUrl);
6588
+ }
6396
6589
  const host = hostOf(credentials.armadaApi.url);
6397
6590
  if (credentials.armadaSignIn?.source.kind === "env")
6398
6591
  io.stderr(`! ${API_KEY_VARIABLE} is set in the environment: it wins over what \`armada login\` stores.
6399
6592
  `);
6400
- if (apiKey)
6593
+ if (o.apiKey)
6401
6594
  return loginWithApiKey(io, credentials);
6402
6595
  const p = paths(io);
6403
6596
  const url = credentials.armadaApi.url;
@@ -6430,7 +6623,13 @@ Then confirm it at ${code.verificationUriComplete}
6430
6623
  return 0;
6431
6624
  }
6432
6625
  async function whoami(io, json) {
6433
- const { credentials } = await loadCredentials(io, { armada: false });
6626
+ let { credentials } = await loadCredentials(io, { armada: false });
6627
+ const [only] = credentials.workerTickets;
6628
+ if (!credentials.armadaSignIn && only && credentials.workerTickets.length === 1)
6629
+ ({ credentials } = await loadCredentials(io, {
6630
+ armada: false,
6631
+ worker: { command: "whoami", project: "", ticket: () => only }
6632
+ }));
6434
6633
  const signIn = requireSignIn(credentials);
6435
6634
  const identity = await apiOf(io, credentials.armadaApi.url).whoami(signIn);
6436
6635
  if (json) {
@@ -6447,7 +6646,8 @@ async function logout(io) {
6447
6646
  const { machine } = await loadCredentials(io, { armada: false });
6448
6647
  const p = paths(io);
6449
6648
  const at = storedAt(machine);
6450
- const stored = [SESSION_TOKEN_VARIABLE, API_KEY_VARIABLE, TURSO_LEASE_VARIABLE].filter((k) => machine.store?.assigned.includes(k));
6649
+ const workers = (machine.store?.assigned ?? []).filter((k) => k.startsWith(WORKER_SESSION_PREFIX));
6650
+ const stored = [SESSION_TOKEN_VARIABLE, API_KEY_VARIABLE, TURSO_LEASE_VARIABLE, ...workers].filter((k) => machine.store?.assigned.includes(k));
6451
6651
  const session = machine.store?.values[SESSION_TOKEN_VARIABLE]?.trim();
6452
6652
  if (session) {
6453
6653
  await apiOf(io, at).signOut({ kind: "session", token: session }).catch((err) => io.stderr(`! the session could not be revoked on Armada (${err instanceof Error ? err.message : String(err)}); it expires on its own
@@ -6458,7 +6658,8 @@ async function logout(io) {
6458
6658
  [SESSION_TOKEN_VARIABLE]: null,
6459
6659
  [API_KEY_VARIABLE]: null,
6460
6660
  [SIGNED_IN_TO_VARIABLE]: null,
6461
- [TURSO_LEASE_VARIABLE]: null
6661
+ [TURSO_LEASE_VARIABLE]: null,
6662
+ ...Object.fromEntries(workers.map((k) => [k, null]))
6462
6663
  });
6463
6664
  io.stdout(`Signed out of ${hostOf(at)}: removed the sign-in from ${p.credentials}.
6464
6665
  `);
@@ -6673,6 +6874,8 @@ async function merge2(io, config, credentials, a, configPath) {
6673
6874
  for (const w of o.warnings)
6674
6875
  io.stderr(`armada: warning: ${w}
6675
6876
  `);
6877
+ if (o.merged)
6878
+ await endWorkerSessions(io, config, credentials, o.ticket.id, "merged", a.json);
6676
6879
  return 0;
6677
6880
  } finally {
6678
6881
  (await turso.live)?.db?.close();
@@ -6890,11 +7093,15 @@ var COMMAND_HELP = {
6890
7093
  effort) and the environment variables to pass, named, never shown.
6891
7094
  The profile follows [[conductor.routing]] on the ticket's labels, then
6892
7095
  default_profile; --profile overrides it, with --reason when it differs.
6893
- --prompt prints only the prompt, for \`--message-file -\`
7096
+ Signed in to Armada, the prompt starts with a one-time launch token, so
7097
+ the worker needs no key. --prompt prints only the prompt, for \`--message-file -\`
6894
7098
  `,
6895
7099
  login: ` login Sign this terminal in to Armada: confirm the code it shows in the browser
6896
7100
  login --api-key Sign a headless coordinator in with an organization API key, read from a
6897
7101
  hidden prompt or standard input (ARMADA_API_KEY in the environment also works)
7102
+ login --launch-token <token> [--api-url <url>]
7103
+ Worker: exchange the one-time token of the launch message for a worker
7104
+ session, which claims, reports, asks and releases that ticket only
6898
7105
  `,
6899
7106
  whoami: ` whoami The person or API key this terminal is signed in as, and its organization
6900
7107
  `,
@@ -6972,7 +7179,9 @@ var VALUE_OPTIONS = [
6972
7179
  "slug",
6973
7180
  "profile",
6974
7181
  "options",
6975
- "timeout"
7182
+ "timeout",
7183
+ "launch-token",
7184
+ "api-url"
6976
7185
  ];
6977
7186
  var FLAG_OPTIONS = ["dry-run", "no-lock", "prompt", "wait", "note", "api-key"];
6978
7187
  var COMMAND_OPTIONS = {
@@ -6985,8 +7194,9 @@ var COMMAND_OPTIONS = {
6985
7194
  init: ["program-root", "name", "slug"],
6986
7195
  merge: ["ticket", "dry-run", "no-lock"],
6987
7196
  brief: ["profile", "reason", "prompt"],
6988
- login: ["api-key"]
7197
+ login: ["api-key", "launch-token", "api-url"]
6989
7198
  };
7199
+ var WORKER_COMMANDS = new Set(["claim", "report", "release", "ask"]);
6990
7200
  function parseArgs(argv) {
6991
7201
  const args = {
6992
7202
  command: null,
@@ -7124,7 +7334,13 @@ async function run(argv, io) {
7124
7334
  if (worker) {
7125
7335
  const { path, text } = await findConfig(io, args.config, args.command);
7126
7336
  const config = parseConfig(text, path);
7127
- const { credentials } = await loadCredentials(io);
7337
+ const command = args.command;
7338
+ const scope = WORKER_COMMANDS.has(command) ? {
7339
+ command,
7340
+ project: config.project.slug,
7341
+ ticket: (stored) => command === "claim" ? args.rest[0]?.toUpperCase() ?? null : currentTicket(io, config, args.options.ticket, stored)
7342
+ } : undefined;
7343
+ const { credentials } = await loadCredentials(io, scope ? { worker: scope } : {});
7128
7344
  return await worker(io, config, credentials, args);
7129
7345
  }
7130
7346
  if (args.command === "merge") {
@@ -7158,7 +7374,11 @@ async function run(argv, io) {
7158
7374
  if (args.rest.length)
7159
7375
  throw new UsageError(`${args.command} takes no argument${args.command === "login" ? ": an API key is read from a hidden prompt or standard input, never from the command line" : ""}`);
7160
7376
  if (args.command === "login")
7161
- return await login(io, args.options["api-key"] === "true");
7377
+ return await login(io, {
7378
+ apiKey: args.options["api-key"] === "true",
7379
+ launchToken: args.options["launch-token"] ?? null,
7380
+ apiUrl: args.options["api-url"] ?? null
7381
+ });
7162
7382
  if (args.command === "logout")
7163
7383
  return await logout(io);
7164
7384
  return await whoami(io, args.json);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@the-vibe-company/armada",
3
- "version": "0.1.17",
3
+ "version": "0.1.18",
4
4
  "type": "module",
5
5
  "description": "Run a fleet of coding agents on one project: the armada command line.",
6
6
  "license": "MIT",