@the-vibe-company/armada 0.1.16 → 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 (3) hide show
  1. package/README.md +6 -4
  2. package/dist/armada.js +337 -62
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -97,21 +97,23 @@ armada release --reason "wrong ticket"
97
97
  - `report` and `release` find the ticket from `--ticket`, then `ARMADA_TICKET`, then the current git branch (`feature/abc-12-…`).
98
98
  - Turso is optional. When it is not configured or not reachable, the commands still write Linear and print a warning.
99
99
 
100
- ## Questions and answers
100
+ ## Plans, questions and answers
101
101
 
102
102
  ```sh
103
103
  armada ask "Which store keeps the sessions? I recommend SQLite." --options "SQLite | Redis" # worker
104
104
  armada inbox # coordinator: what waits, oldest first
105
105
  armada inbox --wait # returns when a new item arrives, or after --timeout (default 300 s)
106
106
  armada answer 12 "SQLite, for the first slice." # after delivering it in the worker's session
107
+ armada answer 13 "approved" # a plan, after delivering approval
107
108
  armada answer --note ABC-12 "main moved: rebase before you ship" # an unsolicited message, same path
108
109
  ```
109
110
 
110
111
  - `ask` reports the `blocked` phase with `Agent status: blocked — question: <first line>` (the rest and the numbered options below it) and adds a `question` item to the coordinator's inbox in Turso. The worker then stops and waits for the answer in its session, and reports the phase it resumes. It finds the ticket like `report`.
111
- - `inbox` lists the coordinator's open items (questions, requests, hand-backs) and silent workers, oldest first. A worker is silent when it holds a ticket, its newest Turso event is older than `policy.silence_minutes`, and its phase does not wait on someone else. It reads Turso only (no Linear key) and records that the coordinator is at work, for the dashboard. `--wait` polls every 5 s and marks the items that were not there before with `*`; loop on it.
112
+ - `report awaiting-approval` adds a `plan` item with the full message and worker handle to the coordinator's inbox. Same-phase heartbeats neither duplicate nor reopen it. Answering it, recording a note, leaving the phase or releasing the ticket closes the plan and any pending approval request. For a pre-approved plan, post the plan with `report implementing` instead: no approval item is needed.
113
+ - `inbox` lists the coordinator's open items (questions, plans, requests, hand-backs) and silent workers, oldest first. A worker is silent when it holds a ticket, its newest Turso event is older than `policy.silence_minutes`, and its phase does not wait on someone else. It reads Turso only (no Linear key) and records that the coordinator is at work, for the dashboard. `--wait` polls every 5 s and marks the items that were not there before with `*`; loop on it.
112
114
  - A coordinator's own claim is never listed as silent in its inbox: only an exact, nonempty handle match is excluded, not its questions, requests or hand-backs. `inbox` takes the reading coordinator's handle from `ARMADA_COORDINATOR_HANDLE` first, otherwise from both `CONDUCTOR_WORKSPACE_ID` and `CONDUCTOR_SESSION_ID` joined as `workspace/session`. Blank values are ignored; with no complete identity, silence detection is unchanged. Local coordinators should set `ARMADA_COORDINATOR_HANDLE` to the handle used for their claim. The same identity is used for every `--wait` poll and the dashboard presence record; the fleet-wide `status` and dashboard silence rules are unchanged.
113
- - `answer` never calls a runtime: deliver the answer first with the runtime guide's message section. It posts `Agent status: <current phase> — answer: …` on the ticket and resolves the item. An item id needs Turso; a ticket id answers that ticket's open questions and also works without Turso. `--note` records a message the worker did not ask for as `Agent status: <phase> — note: …`. These two are the coordinator's records: Armada never reads them as the worker's phase, hand-back or sign of life. Only questions and requests can be answered; `merge` resolves hand-backs, and `release` and `merge` resolve the ticket's open questions. A worker that does not report within `policy.silence_minutes` of an answer shows as silent.
114
- - The dashboard adds two kinds of request, signed by the person who made them. An `answer-request` carries the owner's answer to an open question: deliver it, then `armada answer <request id> "<answer>"`, which resolves the request and its question and names the requester on the ticket (answering the question itself also closes a waiting request). A `launch-request` asks to launch a ready ticket on a profile: launch it as usual; the worker's `armada claim` resolves it and posts who asked. To decline one, `armada answer <request id> "<why>"`: it is closed with the reason and nothing is posted on the ticket.
115
+ - `answer` never calls a runtime: deliver the answer first with the runtime guide's message section. It posts `Agent status: <current phase> — answer: …` on the ticket and resolves the item. An item id needs Turso; a ticket id answers that ticket's open questions and plans and also works without Turso. `--note` records a delivered note as `Agent status: <phase> — note: …`; it accepts a ticket or plan item id and resolves open plans, not questions. These two are the coordinator's records: Armada never reads them as the worker's phase, hand-back or sign of life. Questions, plans and requests can be answered; `merge` resolves hand-backs, and `release` and `merge` resolve the ticket's open questions. A worker that does not report within `policy.silence_minutes` of an answer shows as silent.
116
+ - The dashboard adds two kinds of request, signed by the person who made them. In "Waiting for you", **Approve** opens an editable approval (`approved` by default); sending it creates an `answer-request`, just like answering a question. Deliver its text, then `armada answer <request id> "<answer>"`, which resolves the request and its question or plan and names the requester on the ticket (answering the item itself also closes a waiting request). A `launch-request` asks to launch a ready ticket on a profile: launch it as usual; the worker's `armada claim` resolves it and posts who asked. To decline one, `armada answer <request id> "<why>"`: it is closed with the reason and nothing is posted on the ticket.
115
117
 
116
118
  ## Merge a finished pull request (coordinator)
117
119
 
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)
@@ -2492,6 +2520,15 @@ async function addInboxItem(db, item) {
2492
2520
  });
2493
2521
  return Number(rs.lastInsertRowid);
2494
2522
  }
2523
+ async function putPlan(db, item) {
2524
+ await db.execute({
2525
+ sql: `INSERT INTO inbox_items (project, ticket, kind, recipient, author, body, created_at)
2526
+ SELECT ?, ?, 'plan', 'coordinator', ?, ?, ?
2527
+ WHERE NOT EXISTS (SELECT 1 FROM inbox_items
2528
+ WHERE project = ? AND ticket = ? AND kind = 'plan' AND resolved_at IS NULL)`,
2529
+ args: [item.project, item.ticket, item.author, item.body, item.at.toISOString(), item.project, item.ticket]
2530
+ });
2531
+ }
2495
2532
  async function putHandBack(db, item) {
2496
2533
  const updated = await db.execute({
2497
2534
  sql: `UPDATE inbox_items SET body = ?, author = ?, created_at = ?
@@ -2552,7 +2589,7 @@ async function resolveInboxItem(db, q) {
2552
2589
  async function lastAnsweredAt(db, project) {
2553
2590
  const rs = await db.execute({
2554
2591
  sql: `SELECT ticket, max(resolved_at) AS at FROM inbox_items
2555
- WHERE project = ? AND kind = 'question' AND ticket IS NOT NULL AND resolved_at IS NOT NULL
2592
+ WHERE project = ? AND kind IN ('question', 'plan') AND ticket IS NOT NULL AND resolved_at IS NOT NULL
2556
2593
  GROUP BY ticket`,
2557
2594
  args: [project]
2558
2595
  });
@@ -2575,6 +2612,24 @@ async function resolveAnswerRequests(db, q) {
2575
2612
  });
2576
2613
  return rs.rowsAffected;
2577
2614
  }
2615
+ async function resolvePlans(db, input) {
2616
+ const args = [input.at.toISOString(), input.resolution, input.project, input.ticket];
2617
+ const [, resolved] = await db.batch([
2618
+ {
2619
+ sql: `UPDATE inbox_items SET resolved_at = ?, resolution = ?
2620
+ WHERE project = ? AND kind = 'answer-request' AND resolved_at IS NULL
2621
+ AND id IN (SELECT q.item FROM inbox_requests q JOIN inbox_items i ON i.id = q.question
2622
+ WHERE i.project = ? AND i.ticket = ? AND i.kind = 'plan' AND i.resolved_at IS NULL)`,
2623
+ args: [input.at.toISOString(), input.resolution, input.project, input.project, input.ticket]
2624
+ },
2625
+ {
2626
+ sql: `UPDATE inbox_items SET resolved_at = ?, resolution = ?
2627
+ WHERE project = ? AND ticket = ? AND kind = 'plan' AND resolved_at IS NULL`,
2628
+ args
2629
+ }
2630
+ ], "write");
2631
+ return resolved?.rowsAffected ?? 0;
2632
+ }
2578
2633
  async function acquireLease(db, l) {
2579
2634
  const at = l.at.toISOString();
2580
2635
  const expires = new Date(l.at.getTime() + l.ttlMs).toISOString();
@@ -2933,6 +2988,23 @@ ${body}` : statusLine);
2933
2988
  headSha: sha,
2934
2989
  at
2935
2990
  });
2991
+ if (input.phase === "awaiting-approval" && ticket.agentPhase !== input.phase) {
2992
+ const handle = await getRuntimeHandle(db, config.project.slug, ticket.id);
2993
+ await putPlan(db, {
2994
+ project: config.project.slug,
2995
+ ticket: ticket.id,
2996
+ author: handle && !handle.releasedAt ? handle.handle : null,
2997
+ body: message,
2998
+ at
2999
+ });
3000
+ } else if (input.phase !== "awaiting-approval") {
3001
+ await resolvePlans(db, {
3002
+ project: config.project.slug,
3003
+ ticket: ticket.id,
3004
+ resolution: `worker reported ${input.phase}`,
3005
+ at
3006
+ });
3007
+ }
2936
3008
  if (input.phase === "ready-to-merge")
2937
3009
  await putHandBack(db, {
2938
3010
  project: config.project.slug,
@@ -2964,6 +3036,12 @@ async function releaseTicket(ctx, input) {
2964
3036
  await live(ctx, warnings, "record the release", async (db) => {
2965
3037
  await ensureProject(db, projectOf(config), at);
2966
3038
  await releaseRuntimeHandle(db, config.project.slug, ticket.id, at);
3039
+ await resolvePlans(db, {
3040
+ project: config.project.slug,
3041
+ ticket: ticket.id,
3042
+ resolution: `ticket released: ${input.reason.trim()}`,
3043
+ at
3044
+ });
2967
3045
  await resolveInboxItems(db, {
2968
3046
  project: config.project.slug,
2969
3047
  ticket: ticket.id,
@@ -3124,9 +3202,11 @@ function buildBrief(input) {
3124
3202
  choice?.reason ? ` --reason ${shellWord(choice.reason)}` : ""
3125
3203
  ].join("");
3126
3204
  const has = (name) => !!input.env[name]?.trim();
3205
+ const launch = input.launch ?? null;
3127
3206
  const environment = [
3128
3207
  ...VARIABLES.map((v) => ({
3129
3208
  ...v,
3209
+ ...launch ? { required: false, purpose: `${v.purpose}; not needed: the launch token signs the worker in` } : {},
3130
3210
  value: null,
3131
3211
  inShell: has(v.name),
3132
3212
  inStore: !has(v.name) && !!input.stored?.includes(v.name)
@@ -3157,6 +3237,11 @@ function buildBrief(input) {
3157
3237
  install: `npm install -g ${pkg}`,
3158
3238
  fallback: `npm exec --yes --package=${pkg} -- armada`,
3159
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,
3160
3245
  environment,
3161
3246
  blockers: ticket.blockers.map(({ notes, ...b }) => ({ ...b, handBack: handBackNote(notes) })),
3162
3247
  notes: ticket.notes.slice(0, MAX_NOTES),
@@ -3183,10 +3268,15 @@ function renderPrompt(b) {
3183
3268
  "",
3184
3269
  "```sh",
3185
3270
  b.install,
3271
+ ...b.launch ? [b.launch.command] : [],
3186
3272
  b.claimCommand,
3187
3273
  "```",
3188
3274
  "",
3189
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
+ ] : [],
3190
3280
  "",
3191
3281
  "If the claim is refused, stop and quote the refusal in your reply (usually another worker holds the ticket).",
3192
3282
  "",
@@ -3220,7 +3310,7 @@ ${quote(x.handBack.body)}` : "No hand-back note.", "");
3220
3310
  out.push(`- ${w.id} — ${w.title} (${w.phase})${w.branch ? `, branch \`${w.branch}\`` : ""}${w.pr ? `, ${w.pr}` : ""}`);
3221
3311
  } else
3222
3312
  out.push("None.");
3223
- 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.`);
3224
3314
  return `${out.join(`
3225
3315
  `)}
3226
3316
  `;
@@ -3241,6 +3331,12 @@ async function loadBrief(config, opts) {
3241
3331
  ]);
3242
3332
  if (!ticket)
3243
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}`);
3244
3340
  return buildBrief({
3245
3341
  config,
3246
3342
  ticket,
@@ -3250,6 +3346,8 @@ async function loadBrief(config, opts) {
3250
3346
  version: opts.version,
3251
3347
  env: opts.env,
3252
3348
  ...opts.stored ? { stored: opts.stored } : {},
3349
+ launch: made,
3350
+ noLaunch: missed?.reason ?? null,
3253
3351
  now: now()
3254
3352
  });
3255
3353
  }
@@ -3260,22 +3358,38 @@ var API_KEY_VARIABLE = "ARMADA_API_KEY";
3260
3358
  var API_URL_VARIABLE = "ARMADA_API_URL";
3261
3359
  var SIGNED_IN_TO_VARIABLE = "ARMADA_SIGNED_IN_TO";
3262
3360
  var TURSO_LEASE_VARIABLE = "ARMADA_TURSO_LEASE";
3263
- var formatLease = (lease) => Buffer.from(JSON.stringify(lease), "utf8").toString("base64url");
3264
- 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) {
3265
3365
  if (!value?.trim())
3266
3366
  return null;
3267
3367
  try {
3268
- const l = JSON.parse(Buffer.from(value.trim(), "base64url").toString("utf8"));
3269
- const keys = ["api", "organization", "url", "token", "expiresAt", "revision"];
3270
- if (!keys.every((k) => typeof l[k] === "string" && l[k]))
3271
- return null;
3272
- if (Number.isNaN(Date.parse(String(l.expiresAt))))
3368
+ const r = JSON.parse(Buffer.from(value.trim(), "base64url").toString("utf8"));
3369
+ if (!keys.every((k) => typeof r[k] === "string" && r[k]))
3273
3370
  return null;
3274
- return Object.fromEntries(keys.map((k) => [k, String(l[k])]));
3371
+ return Object.fromEntries(keys.map((k) => [k, String(r[k])]));
3275
3372
  } catch {
3276
3373
  return null;
3277
3374
  }
3278
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
+ }
3279
3393
  function armadaAddress(url) {
3280
3394
  try {
3281
3395
  const u = new URL(url.trim());
@@ -3313,7 +3427,14 @@ var fromEnv = (env, variable) => {
3313
3427
  const value = clean(env[variable]);
3314
3428
  return value ? { value, source: { kind: "env", variable } } : null;
3315
3429
  };
3316
- function resolveCredentials({ env, store = {}, personal, ghToken, armada }) {
3430
+ function resolveCredentials({
3431
+ env,
3432
+ store = {},
3433
+ personal,
3434
+ ghToken,
3435
+ armada,
3436
+ ticket
3437
+ }) {
3317
3438
  const fromStore = (variable) => {
3318
3439
  const value = clean(store[variable]);
3319
3440
  return value ? { value, source: { kind: "store" } } : null;
@@ -3326,14 +3447,23 @@ function resolveCredentials({ env, store = {}, personal, ghToken, armada }) {
3326
3447
  const tursoUrlConfig = clean(personal?.turso.url);
3327
3448
  const apiUrlConfig = clean(personal?.api.url);
3328
3449
  const apiUrl = fromEnv(env, API_URL_VARIABLE);
3329
- 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;
3330
3454
  const envKey = fromEnv(env, API_KEY_VARIABLE);
3331
3455
  const signedInTo = armadaAddress(clean(store[SIGNED_IN_TO_VARIABLE]) ?? DEFAULT_ARMADA_API_URL);
3332
3456
  const here = signedInTo === armadaAddress(armadaApi.url);
3333
3457
  const session = fromStore(SESSION_TOKEN_VARIABLE);
3334
3458
  const storedKey = fromStore(API_KEY_VARIABLE);
3335
3459
  const armadaSignInElsewhere = !here && (session || storedKey) ? signedInTo : null;
3336
- 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;
3337
3467
  const fromArmada = (value, detail) => value && detail ? { value, source: { kind: "armada", detail } } : null;
3338
3468
  const tursoPair = armada?.turso && !fromEnv(env, "ARMADA_TURSO_URL") && !fromEnv(env, "ARMADA_TURSO_TOKEN") ? armada.turso : null;
3339
3469
  const found = {
@@ -3355,7 +3485,8 @@ function resolveCredentials({ env, store = {}, personal, ghToken, armada }) {
3355
3485
  },
3356
3486
  armadaApi,
3357
3487
  armadaSignIn,
3358
- armadaSignInElsewhere: envKey ? null : armadaSignInElsewhere
3488
+ workerTickets: workers.map((w) => w.ticket),
3489
+ armadaSignInElsewhere: envKey || workerHere ? null : armadaSignInElsewhere
3359
3490
  };
3360
3491
  }
3361
3492
  var missingKeys = (credentials) => STORED_KEYS.filter((k) => credentials[k.name] === null);
@@ -3842,7 +3973,7 @@ function statusComment(phase, word, text, ref) {
3842
3973
 
3843
3974
  ${detail}` : line;
3844
3975
  }
3845
- var ANSWERABLE = ["question", "request", "answer-request", "launch-request"];
3976
+ var ANSWERABLE = ["question", "plan", "request", "answer-request", "launch-request"];
3846
3977
  async function answerItem(ctx, input) {
3847
3978
  const { config, linear } = ctx;
3848
3979
  const project = config.project.slug;
@@ -3850,8 +3981,6 @@ async function answerItem(ctx, input) {
3850
3981
  if (!text)
3851
3982
  throw new Refusal(`the ${input.note ? "note" : "answer"} is empty`, input.note ? `armada answer --note ${input.target.trim()} "<message>"` : `armada answer ${input.target.trim()} "<answer>"`);
3852
3983
  const idMatch = input.target.trim().match(ITEM_ID);
3853
- if (input.note && idMatch)
3854
- throw new Refusal("a note goes to a ticket, not to an inbox item", 'armada answer --note <ticket> "<message>"');
3855
3984
  const warnings = [];
3856
3985
  const lines = [];
3857
3986
  let item = null;
@@ -3860,6 +3989,8 @@ async function answerItem(ctx, input) {
3860
3989
  if (idMatch) {
3861
3990
  itemId = Number(idMatch[1]);
3862
3991
  item = await live(ctx, warnings, `read inbox item #${itemId}`, (db) => getInboxItem(db, project, itemId ?? 0));
3992
+ if (input.note && item?.kind !== "plan")
3993
+ throw new Refusal("a note goes to a ticket or a plan, not to another inbox item", 'armada answer --note <ticket> "<message>"');
3863
3994
  if (!item)
3864
3995
  throw new Refusal(warnings.length ? `inbox item #${itemId} cannot be read (${warnings.join("; ")})` : `inbox item #${itemId} does not exist in project ${project}`, warnings.length ? 'armada answer <ticket> "<answer>", to answer by ticket instead' : "armada inbox");
3865
3996
  if (item.resolvedAt)
@@ -3873,13 +4004,15 @@ async function answerItem(ctx, input) {
3873
4004
  ticketId = input.target.trim().toUpperCase();
3874
4005
  if (!input.note) {
3875
4006
  const open = await live(ctx, warnings, `read the open questions of ${ticketId}`, (db) => openInboxItems(db, { project, recipient: "coordinator", ticket: ticketId ?? "" }));
3876
- if (open && !open.some((i) => i.kind === "question"))
3877
- throw new Refusal(`${ticketId} has no open question in the inbox`, `armada answer --note ${ticketId} "<message>", for an unsolicited message`);
4007
+ if (open && !open.some((i) => i.kind === "question" || i.kind === "plan"))
4008
+ throw new Refusal(`${ticketId} has no open question or plan in the inbox`, `armada answer --note ${ticketId} "<message>", for an unsolicited message`);
3878
4009
  }
3879
4010
  }
3880
4011
  if (item?.kind === "launch-request")
3881
4012
  return declineLaunch(ctx, item, text, warnings);
3882
4013
  const question = item?.kind === "answer-request" ? item.request?.question ?? null : null;
4014
+ const answered = question === null ? item : await live(ctx, warnings, `read the item answered by #${item?.id}`, (db) => getInboxItem(db, project, question));
4015
+ const answerKind = answered?.kind === "plan" ? "plan" : "question";
3883
4016
  let url = "";
3884
4017
  if (ticketId) {
3885
4018
  const ticket = await linear.readTicket(ticketId);
@@ -3892,7 +4025,7 @@ async function answerItem(ctx, input) {
3892
4025
  throw new Refusal(`${ticket.id} has no agent phase: no worker holds it, so there is no one to tell`, "armada status, to see which tickets are in flight");
3893
4026
  warnings.push(`${ticket.id} has no agent phase (no worker holds it); the answer was not posted on the ticket`);
3894
4027
  } else {
3895
- const ref = item?.kind === "answer-request" ? `Answers ${question === null ? "the open question" : `question #${question}`}, as ${item.author ?? "the owner"} asked from the dashboard (request #${item.id}).` : itemId === null ? null : `Answers question #${itemId}.`;
4028
+ const ref = item?.kind === "answer-request" ? `Answers ${question === null ? "the open question or plan" : `${answerKind} #${question}`}, as ${item.author ?? "the owner"} asked from the dashboard (request #${item.id}).` : itemId === null ? null : `Answers ${answerKind} #${itemId}.`;
3896
4029
  await linear.comment(ticket.uuid, statusComment(ticket.agentPhase, input.note ? "note" : "answer", text, ref));
3897
4030
  lines.push(`${input.note ? "Note" : "Answer"} posted on ${ticket.id} (${ticket.agentPhase}).`);
3898
4031
  }
@@ -3901,6 +4034,8 @@ async function answerItem(ctx, input) {
3901
4034
  const recorded = await live(ctx, warnings, `record the ${input.note ? "note" : "answer"}`, async (db) => {
3902
4035
  await ensureProject(db, projectOf(config), at);
3903
4036
  if (input.note) {
4037
+ if (ticketId)
4038
+ await resolvePlans(db, { project, ticket: ticketId, resolution: text, at });
3904
4039
  const id = await addInboxItem(db, {
3905
4040
  project,
3906
4041
  ticket: ticketId,
@@ -3916,17 +4051,18 @@ async function answerItem(ctx, input) {
3916
4051
  if (item?.kind === "answer-request") {
3917
4052
  await resolveInboxItem(db, { project, id: item.id, resolution: text, at });
3918
4053
  const closed = question !== null && await resolveInboxItem(db, { project, id: question, resolution: text, at });
3919
- return `Dashboard request #${item.id} delivered${closed ? `; question #${question} resolved` : ""}.`;
4054
+ return `Dashboard request #${item.id} delivered${closed ? `; ${answerKind} #${question} resolved` : ""}.`;
3920
4055
  }
3921
4056
  if (itemId !== null) {
3922
4057
  const done = await resolveInboxItem(db, { project, id: itemId, resolution: text, at });
3923
- if (item?.kind === "question")
4058
+ if (item?.kind === "question" || item?.kind === "plan")
3924
4059
  await resolveAnswerRequests(db, { project, question: itemId, resolution: text, at });
3925
4060
  return done ? `Inbox item #${itemId} resolved.` : `Inbox item #${itemId} was already resolved.`;
3926
4061
  }
3927
4062
  const n = await resolveInboxItems(db, { project, ticket: ticketId ?? "", kind: "question", resolution: text, at });
4063
+ const plans = await resolvePlans(db, { project, ticket: ticketId ?? "", resolution: text, at });
3928
4064
  await resolveInboxItems(db, { project, ticket: ticketId ?? "", kind: "answer-request", resolution: text, at });
3929
- return `${n} open question${n === 1 ? "" : "s"} of ${ticketId} resolved.`;
4065
+ return `${n} open question${n === 1 ? "" : "s"}${plans ? ` and ${plans} plan${plans === 1 ? "" : "s"}` : ""} of ${ticketId} resolved.`;
3930
4066
  });
3931
4067
  if (recorded)
3932
4068
  lines.push(recorded);
@@ -4838,10 +4974,10 @@ A coordinator may start cold, on a laptop or in a fresh cloud session, with noth
4838
4974
 
4839
4975
  ## Loop
4840
4976
 
4841
- 1. **Read the fleet** with \`armada status\` and \`armada inbox\`, never from memory. Done when you can name every ticket in flight and its phase, every ready ticket, every pull request waiting, every silent worker and every pending question or request.
4842
- 2. **Answer what waits for you first.** For each question in \`armada inbox\`: decide it, or escalate it to the owner when it is a product decision and wait for theirs. Deliver the answer in the worker's session with the runtime guide's *message* section, then record it with \`armada answer <item> "<decision and reason>"\`. \`armada answer\` only records; it never reaches the worker. Decide reversible choices yourself and prefer the option that keeps behaviour observable. When two workers need the same shared resource (a migration slot, a generated file, a version number), set the rule once and tell both. A message the worker did not ask for (main moved, rebase needed) takes the same path: deliver it with the runtime guide, then \`armada answer --note <ticket> "<message>"\`. Done when the inbox shows no open question.
4977
+ 1. **Read the fleet** with \`armada status\` and \`armada inbox\`, never from memory. Done when you can name every ticket in flight and its phase, every ready ticket, every pull request waiting, every silent worker and every pending question, plan or request.
4978
+ 2. **Answer what waits for you first.** For each question in \`armada inbox\`: decide it, or escalate it to the owner when it is a product decision and wait for theirs. For each \`plan\` item: read the full plan, approve it or give concrete amendments. Deliver the decision in the worker's session with the runtime guide's *message* section, then record it with \`armada answer <item> "approved"\` or \`armada answer <item> "<amendments and reason>"\`. The worker resumes with \`implementing\` on approval, or returns to \`planning\` and submits a revised plan. \`armada answer\` only records; it never reaches the worker. Decide reversible choices yourself and prefer the option that keeps behaviour observable. When two workers need the same shared resource (a migration slot, a generated file, a version number), set the rule once and tell both. A message the worker did not ask for (main moved, rebase needed) takes the same path: deliver it with the runtime guide, then \`armada answer --note <ticket> "<message>"\`. Done when the inbox shows no open question or plan.
4843
4979
  3. **Carry out the owner's dashboard requests.** They are the owner's word, signed with their name; they never reached a worker.
4844
- - \`answer-request\` (it names the question it answers, \`answers #<id>\`): deliver its text in the worker's session with the runtime guide's *message* section, as the owner's answer, then \`armada answer <request id> "<the text you delivered>"\`. That resolves the request and its question, and the ticket names who answered. If the question is gone (the worker was released), \`armada answer <request id> "<why>"\` closes it.
4980
+ - \`answer-request\` (it names the question or plan it answers, \`answers #<id>\`): deliver its text in the worker's session with the runtime guide's *message* section, as the owner's answer or plan approval, then \`armada answer <request id> "<the text you delivered>"\`. That resolves the request and its question or plan, and the ticket names who answered. If the item is gone (the worker was released or changed phase), \`armada answer <request id> "<why>"\` closes it.
4845
4981
  - \`launch-request\` (it names the profile the owner chose): launch the ticket as in step 5, with that profile. When it differs from the routed one, the request's body gives the \`--profile\` and \`--reason\` to pass to \`armada brief\` and to the worker's claim. The worker's \`armada claim\` resolves the request and posts who asked. If the ticket must not start (it collides with work in flight, or its plan changed), decline it: \`armada answer <request id> "<why>"\`, and tell the owner in your report.
4846
4982
  Done when the inbox shows no open request.
4847
4983
  4. **Check silent workers** with the runtime guide's *status* section. A worker that is still working gets a nudge to report; a worker that died is relaunched or its ticket released.
@@ -4887,9 +5023,9 @@ You are a worker. You own exactly one ticket, named in your launch brief. You tu
4887
5023
 
4888
5024
  ## Steps
4889
5025
 
4890
- 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.
4891
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.
4892
- 3. **Plan.** Write the plan: what changes, how it is tested, and the checks a person could observe when it is done. If your brief says plans are pre-approved, post it with \`armada report implementing --message "<plan>"\` and go on. Otherwise post it with \`armada report awaiting-approval --message "<plan>"\`, push your branch, and wait for the coordinator's answer in your session.
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.
4893
5029
  4. **Implement** test-first. A material change to the approved plan needs a new approval.
4894
5030
  5. **Ship.** \`armada report shipping --pr <number>\`. Use the \`ship-pr-dev\` skill when the repository has it; otherwise run the repository's local checks, open the pull request with a Commitizen title (\`feat(scope): …\`), link it on the ticket, and fix CI until every required check is green.
4895
5031
  6. **Rebase** on the latest default branch right before hand-back, and get CI green on that final head.
@@ -5270,7 +5406,7 @@ async function loadStatus(config, opts) {
5270
5406
  });
5271
5407
  }
5272
5408
  // package.json
5273
- var version = "0.1.16";
5409
+ var version = "0.1.18";
5274
5410
 
5275
5411
  // src/io.ts
5276
5412
  class UsageError extends Error {
@@ -5300,7 +5436,7 @@ var fromLease = (lease) => ({
5300
5436
  token: lease.token,
5301
5437
  detail: `a token made for this terminal, expires ${hhmm(lease.expiresAt)}`
5302
5438
  });
5303
- async function fromArmada(io, machine, credentials) {
5439
+ async function fromArmada(io, machine, credentials, purpose) {
5304
5440
  const signIn = credentials.armadaSignIn;
5305
5441
  if (!signIn)
5306
5442
  return null;
@@ -5316,12 +5452,14 @@ async function fromArmada(io, machine, credentials) {
5316
5452
  };
5317
5453
  let answer;
5318
5454
  try {
5319
- 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);
5320
5456
  } catch (err) {
5321
5457
  if (!(err instanceof ArmadaApiError))
5322
5458
  throw err;
5323
5459
  if (err.signedOut || err.status === 403) {
5324
5460
  await keep(null);
5461
+ if (signIn.kind === "worker")
5462
+ throw err;
5325
5463
  io.stderr(`! Armada gave no keys (${err.message}); using this machine's${err.next ? `. Next: ${err.next}` : ""}
5326
5464
  `);
5327
5465
  return null;
@@ -5360,8 +5498,15 @@ async function fromArmada(io, machine, credentials) {
5360
5498
  turso: t?.kind === "stored" ? { url: t.url, token: t.token, detail: `the stored Turso access of ${answer.organization.name}` } : null
5361
5499
  };
5362
5500
  }
5363
- async function loadCredentials(io, { armada = true } = {}) {
5501
+ async function loadCredentials(io, { armada = true, worker } = {}) {
5364
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
+ }
5365
5510
  let gh;
5366
5511
  const sources = {
5367
5512
  env: io.env,
@@ -5371,12 +5516,21 @@ async function loadCredentials(io, { armada = true } = {}) {
5371
5516
  return gh;
5372
5517
  },
5373
5518
  ...machine.store ? { store: machine.store.values } : {},
5374
- ...machine.personal ? { personal: machine.personal.config } : {}
5519
+ ...machine.personal ? { personal: machine.personal.config } : {},
5520
+ ticket
5375
5521
  };
5376
5522
  const local = resolveCredentials(sources);
5377
- 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))
5378
5532
  return { machine, credentials: local };
5379
- const keys = await fromArmada(io, machine, local);
5533
+ const keys = await fromArmada(io, machine, local, purpose);
5380
5534
  return { machine, credentials: keys ? resolveCredentials({ ...sources, armada: keys }) : local };
5381
5535
  }
5382
5536
  var describeSource = (s) => {
@@ -5480,8 +5634,9 @@ function buildAuthStatus(machine, credentials) {
5480
5634
  personalConfig: machine.paths && machine.personal ? { path: machine.paths.config, exists: machine.personal.exists } : null,
5481
5635
  signIn: {
5482
5636
  api: credentials.armadaApi,
5483
- method: credentials.armadaSignIn?.kind ?? null,
5484
- 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
5485
5640
  },
5486
5641
  warnings: storeWarnings(machine)
5487
5642
  };
@@ -5504,6 +5659,8 @@ function renderAuthStatus(status) {
5504
5659
  const api = signIn.api.source.kind === "default" ? "built in" : describeSource(signIn.api.source);
5505
5660
  lines.push("", "Armada sign-in", ` API ${signIn.api.url} (${api})`);
5506
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`);
5507
5664
  return `${lines.join(`
5508
5665
  `)}
5509
5666
  `;
@@ -5548,6 +5705,7 @@ function renderBrief(b) {
5548
5705
  ...b.routing ? [`Chosen by: ${b.routing.why}`] : [],
5549
5706
  `Repository: ${b.repository.url}`,
5550
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`}`,
5551
5709
  "",
5552
5710
  "Environment to pass (values are never printed):",
5553
5711
  ...b.environment.map((v) => {
@@ -5562,6 +5720,29 @@ function renderBrief(b) {
5562
5720
  return out.join(`
5563
5721
  `);
5564
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
+ }
5565
5746
  async function brief2(io, config, credentials, a, version) {
5566
5747
  const [ticket, ...extra] = a.rest;
5567
5748
  if (!ticket)
@@ -5594,6 +5775,7 @@ async function brief2(io, config, credentials, a, version) {
5594
5775
  version,
5595
5776
  env: io.env,
5596
5777
  stored: STORED_KEYS.filter((k) => credentials.sources[k.name]?.kind === "store").map((k) => k.variable),
5778
+ launch: launcher(io, config, credentials),
5597
5779
  ...io.fetch ? { fetch: io.fetch } : {},
5598
5780
  ...io.now ? { now: io.now } : {}
5599
5781
  });
@@ -5822,12 +6004,12 @@ function statusEvents(config, credentials) {
5822
6004
  }
5823
6005
  };
5824
6006
  }
5825
- function currentTicket(io, config, explicit) {
6007
+ function currentTicket(io, config, explicit, workers = []) {
5826
6008
  const fromEnv = io.env.ARMADA_TICKET?.trim();
5827
6009
  const id = explicit?.trim() || fromEnv || (() => {
5828
6010
  const branch = io.gitBranch?.();
5829
6011
  return branch ? ticketFromBranch(branch, config.tracker.programRoot) : null;
5830
- })();
6012
+ })() || (workers.length === 1 ? workers[0] : null);
5831
6013
  if (!id)
5832
6014
  throw new UsageError("which ticket? pass --ticket <id>, set ARMADA_TICKET, or run on the ticket's branch");
5833
6015
  return id.toUpperCase();
@@ -5955,7 +6137,7 @@ async function report(io, config, credentials, a) {
5955
6137
  const message = await readMessage(io, a.options);
5956
6138
  if (!message?.trim() && phase !== "ready-to-merge")
5957
6139
  throw new UsageError("--message is required: what you did or what you are doing (first line = summary)");
5958
- const ticket = currentTicket(io, config, a.options.ticket);
6140
+ const ticket = currentTicket(io, config, a.options.ticket, credentials.workerTickets);
5959
6141
  return withContext(io, config, credentials, a.json, (ctx) => reportPhase(ctx, {
5960
6142
  ticket,
5961
6143
  phase,
@@ -5970,8 +6152,35 @@ async function release(io, config, credentials, a) {
5970
6152
  const reason = a.options.reason?.trim();
5971
6153
  if (!reason)
5972
6154
  throw new UsageError("--reason is required: why the ticket is given back");
5973
- const ticket = currentTicket(io, config, a.options.ticket);
5974
- 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
+ }
5975
6184
  }
5976
6185
 
5977
6186
  // src/inbox.ts
@@ -5987,7 +6196,7 @@ async function ask(io, config, credentials, a) {
5987
6196
  if (!question?.trim())
5988
6197
  throw new UsageError('ask needs a question: armada ask "<question, the options, your recommendation>"');
5989
6198
  const options = (a.options.options ?? "").split("|").map((o) => o.trim()).filter(Boolean);
5990
- const ticket = currentTicket(io, config, a.options.ticket);
6199
+ const ticket = currentTicket(io, config, a.options.ticket, credentials.workerTickets);
5991
6200
  return withContext(io, config, credentials, a.json, (ctx) => askCoordinator(ctx, { ticket, question, options }));
5992
6201
  }
5993
6202
  async function answer(io, config, credentials, a) {
@@ -6032,7 +6241,7 @@ function renderInbox(r) {
6032
6241
  out.push(`${e.new ? "* " : " "}${head}`, ...e.body.split(`
6033
6242
  `).map((l) => l ? ` ${l}` : ""));
6034
6243
  }
6035
- if (r.items.some((e) => e.kind === "question"))
6244
+ if (r.items.some((e) => e.kind === "question" || e.kind === "plan"))
6036
6245
  out.push(`Deliver each answer in the worker's session with the runtime guide, then record it: armada answer <id> "<answer>".`);
6037
6246
  if (r.items.some((e) => e.kind === "answer-request" || e.kind === "launch-request"))
6038
6247
  out.push('Dashboard requests: deliver an answer-request, then armada answer <id> "<answer>"; launch a launch-request (its claim resolves it), or decline it with armada answer <id> "<why>".');
@@ -6296,6 +6505,10 @@ function describeIdentity(identity) {
6296
6505
  const key = identity.apiKey?.name ?? identity.apiKey?.start ?? "an API key";
6297
6506
  return `the API key "${key}" of ${org}`;
6298
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
+ }
6299
6512
  const who = identity.user ? identity.user.name ? `${identity.user.name} <${identity.user.email}>` : identity.user.email : "?";
6300
6513
  return `${who}, ${org}`;
6301
6514
  }
@@ -6336,13 +6549,48 @@ The key is stored in ${p.credentials}.
6336
6549
  `);
6337
6550
  return 0;
6338
6551
  }
6339
- 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");
6340
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
+ }
6341
6589
  const host = hostOf(credentials.armadaApi.url);
6342
6590
  if (credentials.armadaSignIn?.source.kind === "env")
6343
6591
  io.stderr(`! ${API_KEY_VARIABLE} is set in the environment: it wins over what \`armada login\` stores.
6344
6592
  `);
6345
- if (apiKey)
6593
+ if (o.apiKey)
6346
6594
  return loginWithApiKey(io, credentials);
6347
6595
  const p = paths(io);
6348
6596
  const url = credentials.armadaApi.url;
@@ -6375,7 +6623,13 @@ Then confirm it at ${code.verificationUriComplete}
6375
6623
  return 0;
6376
6624
  }
6377
6625
  async function whoami(io, json) {
6378
- 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
+ }));
6379
6633
  const signIn = requireSignIn(credentials);
6380
6634
  const identity = await apiOf(io, credentials.armadaApi.url).whoami(signIn);
6381
6635
  if (json) {
@@ -6392,7 +6646,8 @@ async function logout(io) {
6392
6646
  const { machine } = await loadCredentials(io, { armada: false });
6393
6647
  const p = paths(io);
6394
6648
  const at = storedAt(machine);
6395
- 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));
6396
6651
  const session = machine.store?.values[SESSION_TOKEN_VARIABLE]?.trim();
6397
6652
  if (session) {
6398
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
@@ -6403,7 +6658,8 @@ async function logout(io) {
6403
6658
  [SESSION_TOKEN_VARIABLE]: null,
6404
6659
  [API_KEY_VARIABLE]: null,
6405
6660
  [SIGNED_IN_TO_VARIABLE]: null,
6406
- [TURSO_LEASE_VARIABLE]: null
6661
+ [TURSO_LEASE_VARIABLE]: null,
6662
+ ...Object.fromEntries(workers.map((k) => [k, null]))
6407
6663
  });
6408
6664
  io.stdout(`Signed out of ${hostOf(at)}: removed the sign-in from ${p.credentials}.
6409
6665
  `);
@@ -6618,6 +6874,8 @@ async function merge2(io, config, credentials, a, configPath) {
6618
6874
  for (const w of o.warnings)
6619
6875
  io.stderr(`armada: warning: ${w}
6620
6876
  `);
6877
+ if (o.merged)
6878
+ await endWorkerSessions(io, config, credentials, o.ticket.id, "merged", a.json);
6621
6879
  return 0;
6622
6880
  } finally {
6623
6881
  (await turso.live)?.db?.close();
@@ -6811,16 +7069,16 @@ var COMMAND_HELP = {
6811
7069
  for the answer in your session, and report the phase you resume
6812
7070
  `,
6813
7071
  inbox: ` inbox [--wait [--timeout <seconds>]]
6814
- Coordinator: open questions, requests, hand-backs and silent workers,
7072
+ Coordinator: open questions, plans, requests, hand-backs and silent workers,
6815
7073
  oldest first; records that the coordinator is at work. --wait returns
6816
7074
  when a new item arrives or after --timeout (default 300 s). Needs Turso
6817
7075
  `,
6818
7076
  answer: ` answer <item|ticket> "<answer>"
6819
7077
  Coordinator: record an answer already delivered in the worker's
6820
- session (runtime guide): resolves the question and posts it on the
6821
- ticket. A ticket id answers its open questions. Never calls a runtime
6822
- answer --note <ticket> "<message>"
6823
- Coordinator: record an unsolicited message delivered to a worker
7078
+ session (runtime guide): resolves the question or plan and posts it on
7079
+ the ticket. A ticket id answers its open questions and plans. Never calls a runtime
7080
+ answer --note <ticket|plan item> "<message>"
7081
+ Coordinator: record a delivered note; an open plan is resolved
6824
7082
  `,
6825
7083
  merge: ` merge <pr> [--ticket <id>] [--dry-run] [--no-lock]
6826
7084
  Coordinator: check a handed-back pull request (hand-back SHA = head,
@@ -6835,11 +7093,15 @@ var COMMAND_HELP = {
6835
7093
  effort) and the environment variables to pass, named, never shown.
6836
7094
  The profile follows [[conductor.routing]] on the ticket's labels, then
6837
7095
  default_profile; --profile overrides it, with --reason when it differs.
6838
- --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 -\`
6839
7098
  `,
6840
7099
  login: ` login Sign this terminal in to Armada: confirm the code it shows in the browser
6841
7100
  login --api-key Sign a headless coordinator in with an organization API key, read from a
6842
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
6843
7105
  `,
6844
7106
  whoami: ` whoami The person or API key this terminal is signed in as, and its organization
6845
7107
  `,
@@ -6917,7 +7179,9 @@ var VALUE_OPTIONS = [
6917
7179
  "slug",
6918
7180
  "profile",
6919
7181
  "options",
6920
- "timeout"
7182
+ "timeout",
7183
+ "launch-token",
7184
+ "api-url"
6921
7185
  ];
6922
7186
  var FLAG_OPTIONS = ["dry-run", "no-lock", "prompt", "wait", "note", "api-key"];
6923
7187
  var COMMAND_OPTIONS = {
@@ -6930,8 +7194,9 @@ var COMMAND_OPTIONS = {
6930
7194
  init: ["program-root", "name", "slug"],
6931
7195
  merge: ["ticket", "dry-run", "no-lock"],
6932
7196
  brief: ["profile", "reason", "prompt"],
6933
- login: ["api-key"]
7197
+ login: ["api-key", "launch-token", "api-url"]
6934
7198
  };
7199
+ var WORKER_COMMANDS = new Set(["claim", "report", "release", "ask"]);
6935
7200
  function parseArgs(argv) {
6936
7201
  const args = {
6937
7202
  command: null,
@@ -7069,7 +7334,13 @@ async function run(argv, io) {
7069
7334
  if (worker) {
7070
7335
  const { path, text } = await findConfig(io, args.config, args.command);
7071
7336
  const config = parseConfig(text, path);
7072
- 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 } : {});
7073
7344
  return await worker(io, config, credentials, args);
7074
7345
  }
7075
7346
  if (args.command === "merge") {
@@ -7103,7 +7374,11 @@ async function run(argv, io) {
7103
7374
  if (args.rest.length)
7104
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" : ""}`);
7105
7376
  if (args.command === "login")
7106
- 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
+ });
7107
7382
  if (args.command === "logout")
7108
7383
  return await logout(io);
7109
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.16",
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",