@moxxy/cli 0.40.0 → 0.41.0

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/bin.js +1213 -408
  2. package/package.json +2 -2
package/dist/bin.js CHANGED
@@ -8,12 +8,14 @@ import path3__default, { join, dirname, resolve, relative, isAbsolute, posix, se
8
8
  import { ensurePrivateDir, moxxyHome, pruneStaleTempFiles, moxxyPath, hasProxy, installEgressProxy, readProxyEnv, writeFileAtomic, ensurePrivateFile, resolveChannelToken, rotateChannelToken, liveChannelStatus, spawnDedicatedChannel, stopDedicatedChannel, clearChannelStatus, MOXXY_WS_SUBPROTOCOL, bearerTokenMatches, PRIVATE_FILE_MODE, bearerGuard, tokenFromWsProtocolHeader, resolveOsPrincipal, redactProxyUrl, resolveExecutableTarget, spawnExecutableTarget, listLiveChannelStatuses, writeSignedNetworkCacheAtomic, CrossProcessFireLock, writeChannelStatus, writeBoundedNetworkCacheAtomicSync, writeBoundedDataCacheAtomic, readRequestBody } from '@moxxy/sdk/server';
9
9
  import { spawn, execFile, spawnSync } from 'child_process';
10
10
  import { fileURLToPath, pathToFileURL } from 'url';
11
- import { MoxxyError, createMutex, defineMode, definePlugin, defineChannel, defineViewRenderer, DEFAULT_VIEW_TAGS, defineTunnelProvider, defineAuditExporter, defineAuditSink, z as z$1, defineTool, defineCommand, defineEmbedder, asPluginId, runReactLoop, createDeferredPermissionResolver, isSafeViewUrl, redactSecrets, asTurnId, defineCompactor, abortError, activeCompactionRanges, defineCacheStrategy, denyByDefaultResolver, runManualCompaction, assertDefined, defineWorkflowExecutor, MOXXY_PCM16_24KHZ_MIME, isFileDiffDisplay, summarizeWithProvider, toolResultBytes, isSelectableMode, summarizeSessionTokensFromEvents, summarizeTokensByModel, getInstallHint, toDiffRows, diffGutterNo, fileDiffVerb, fileDiffSummary, computeElisionState, toolResultStubbed, toolResultStub, conversationalStubbed, conversationalStub, isFirstPartyPackage, REDACTED_PLACEHOLDER, isSecretKey, addModelTotals, skillFrontmatterSchema, asSkillId, parseFrontmatter, createCallbackResolver, createAllowListResolver, countNodes, autoAllowResolver, SESSION_SOURCES, startChannelWith, EXIT_AFTER_PAIR_FLAG, renderFrontmatter, formatPrincipal, aggregateCapabilitySpecs, hostCredentialName, moxxyPackageSchema, auditActionOf, verifyEd25519, defineSecretProvider, encodeLoginAuthUrl, redactSecretText, encodeLoginPrompt, ISOLATION_RANK, sleepWithAbort, asSessionId, migrateModeName, asToolCallId, parseFrontmatterFile, createJsonFileStore, evaluateToolRule, asEventId } from '@moxxy/sdk';
11
+ import { MoxxyError, createMutex, defineMode, definePlugin, defineChannel, defineViewRenderer, DEFAULT_VIEW_TAGS, defineTunnelProvider, defineAuditExporter, defineAuditSink, z as z$1, defineTool, defineCommand, defineEmbedder, asPluginId, runReactLoop, createDeferredPermissionResolver, isSafeViewUrl, redactSecrets, asTurnId, defineCompactor, abortError, activeCompactionRanges, defineCacheStrategy, denyByDefaultResolver, runManualCompaction, assertDefined, defineWorkflowExecutor, MOXXY_PCM16_24KHZ_MIME, isFileDiffDisplay, summarizeWithProvider, toolResultBytes, isSelectableMode, summarizeSessionTokensFromEvents, summarizeTokensByModel, getInstallHint, toDiffRows, diffGutterNo, fileDiffVerb, fileDiffSummary, computerControlCommandSchema, computeElisionState, toolResultStubbed, toolResultStub, conversationalStubbed, conversationalStub, isFirstPartyPackage, REDACTED_PLACEHOLDER, isSecretKey, addModelTotals, skillFrontmatterSchema, asSkillId, parseFrontmatter, createCallbackResolver, createAllowListResolver, countNodes, autoAllowResolver, SESSION_SOURCES, startChannelWith, EXIT_AFTER_PAIR_FLAG, renderFrontmatter, formatPrincipal, aggregateCapabilitySpecs, hostCredentialName, moxxyPackageSchema, auditActionOf, asToolCallId, dispatchToolCall, verifyEd25519, defineSecretProvider, encodeLoginAuthUrl, redactSecretText, encodeLoginPrompt, ISOLATION_RANK, sleepWithAbort, asSessionId, migrateModeName, parseFrontmatterFile, createJsonFileStore, computerControlSnapshotSchema, computerApprovalFocusSchema, workflowApprovalItemsSchema, evaluateToolRule, asEventId } from '@moxxy/sdk';
12
12
  import * as os from 'os';
13
13
  import os__default, { homedir, tmpdir, userInfo } from 'os';
14
14
  import { createRequire as createRequire$1 } from 'module';
15
15
  import { z } from 'zod';
16
- import { readFile, realpath, rm, mkdtemp, writeFile, mkdir, open, rename, readdir, unlink, stat, access, constants as constants$2 } from 'fs/promises';
16
+ import { AsyncLocalStorage } from 'async_hooks';
17
+ import { readFile, realpath, rm, mkdtemp, writeFile, mkdir, open, readdir, unlink, link, rename, stat, access, constants as constants$2 } from 'fs/promises';
18
+ import { setTimeout as setTimeout$1 } from 'timers/promises';
17
19
  import { promisify, stripVTControlCharacters } from 'util';
18
20
  import * as readline from 'readline/promises';
19
21
  import { createServer } from 'http';
@@ -21,7 +23,6 @@ import net2, { createConnection, connect } from 'net';
21
23
  import { Worker } from 'worker_threads';
22
24
  import { Buffer as Buffer$1 } from 'buffer';
23
25
  import { StringDecoder } from 'string_decoder';
24
- import { AsyncLocalStorage } from 'async_hooks';
25
26
  import N2, { env, cwd, stdout, stdin } from 'process';
26
27
  import { Stream, PassThrough } from 'stream';
27
28
  import tty, { ReadStream } from 'tty';
@@ -6598,14 +6599,14 @@ var init_jsonl_event_store = __esm({
6598
6599
  init_persistence();
6599
6600
  jsonlEventStore = {
6600
6601
  name: "jsonl",
6601
- open(scope) {
6602
+ open(scope2) {
6602
6603
  return new SessionPersistence({
6603
- sessionId: scope.sessionId,
6604
- cwd: scope.cwd,
6605
- ...scope.dir ? { dir: scope.dir } : {},
6606
- ...scope.providerName ? { providerName: scope.providerName } : {},
6607
- ...scope.modelId ? { modelId: scope.modelId } : {},
6608
- ...scope.source ? { source: scope.source } : {}
6604
+ sessionId: scope2.sessionId,
6605
+ cwd: scope2.cwd,
6606
+ ...scope2.dir ? { dir: scope2.dir } : {},
6607
+ ...scope2.providerName ? { providerName: scope2.providerName } : {},
6608
+ ...scope2.modelId ? { modelId: scope2.modelId } : {},
6609
+ ...scope2.source ? { source: scope2.source } : {}
6609
6610
  });
6610
6611
  },
6611
6612
  restore: (sessionId, dir) => restoreEvents(sessionId, dir),
@@ -7070,6 +7071,18 @@ var init_resolvers = __esm({
7070
7071
  "../core/dist/permissions/resolvers.js"() {
7071
7072
  }
7072
7073
  });
7074
+ function withPermissionScope(resolver, run2) {
7075
+ return scope.run(resolver, run2);
7076
+ }
7077
+ function currentPermissionScope() {
7078
+ return scope.getStore();
7079
+ }
7080
+ var scope;
7081
+ var init_scope = __esm({
7082
+ "../core/dist/permissions/scope.js"() {
7083
+ scope = new AsyncLocalStorage();
7084
+ }
7085
+ });
7073
7086
  function wrapWithPolicy(inner, engine, getToolRule, cwd2) {
7074
7087
  const policyDecision = async (call) => {
7075
7088
  const policy = engine.check(call);
@@ -7084,12 +7097,21 @@ function wrapWithPolicy(inner, engine, getToolRule, cwd2) {
7084
7097
  const decided = await policyDecision(call);
7085
7098
  if (decided)
7086
7099
  return decided;
7087
- return target.check(call, ctx);
7100
+ return (currentPermissionScope() ?? target).check(call, ctx);
7088
7101
  };
7089
7102
  }
7090
7103
  if (prop === "policyCheck") {
7091
7104
  return async (call) => policyDecision(call);
7092
7105
  }
7106
+ if (prop === "mandatoryCheck") {
7107
+ return async (call, ctx) => {
7108
+ const scoped = currentPermissionScope();
7109
+ if (!scoped)
7110
+ return null;
7111
+ const policy = await policyDecision(call);
7112
+ return policy ?? scoped.check(call, ctx);
7113
+ };
7114
+ }
7093
7115
  return Reflect.get(target, prop, receiver);
7094
7116
  }
7095
7117
  });
@@ -7103,8 +7125,8 @@ async function evaluateWorkspaceToolRule(rule, call, cwd2) {
7103
7125
  return evaluateToolRule(unscopedRule, call);
7104
7126
  }
7105
7127
  async function pathsStayInWorkspace(rule, call, cwd2) {
7106
- const scope = rule.workspace;
7107
- if (!scope)
7128
+ const scope2 = rule.workspace;
7129
+ if (!scope2)
7108
7130
  return true;
7109
7131
  const input = isRecord(call.input) ? call.input : {};
7110
7132
  let workspace;
@@ -7113,7 +7135,7 @@ async function pathsStayInWorkspace(rule, call, cwd2) {
7113
7135
  } catch {
7114
7136
  return false;
7115
7137
  }
7116
- for (const pathInput of scope.pathInputs) {
7138
+ for (const pathInput of scope2.pathInputs) {
7117
7139
  const value2 = input[pathInput.key];
7118
7140
  if (value2 === void 0 && pathInput.defaultToWorkspace)
7119
7141
  continue;
@@ -7173,6 +7195,7 @@ var init_session = __esm({
7173
7195
  init_requirements();
7174
7196
  init_engine();
7175
7197
  init_resolvers();
7198
+ init_scope();
7176
7199
  init_logger();
7177
7200
  init_registry();
7178
7201
  Session = class {
@@ -7446,8 +7469,8 @@ var init_session = __esm({
7446
7469
  this.log.clear();
7447
7470
  }
7448
7471
  /**
7449
- * Graceful shutdown: fire every plugin's `onShutdown` hook, then abort
7450
- * the session. Idempotent — safe to call multiple times (subsequent
7472
+ * Graceful shutdown: cancel in-flight work before awaiting plugin shutdown
7473
+ * hooks. Idempotent — safe to call multiple times (subsequent
7451
7474
  * calls are no-ops once `closed` is set).
7452
7475
  *
7453
7476
  * Channels' SIGINT handlers should call this before exiting so plugins
@@ -7457,6 +7480,7 @@ var init_session = __esm({
7457
7480
  if (this.closed)
7458
7481
  return;
7459
7482
  this.closed = true;
7483
+ this.abort(reason);
7460
7484
  try {
7461
7485
  try {
7462
7486
  await this.surfaces.closeAll();
@@ -7490,6 +7514,9 @@ var init_session = __esm({
7490
7514
  get providerAdmin() {
7491
7515
  return this.services.get("providerAdmin");
7492
7516
  }
7517
+ get computerControl() {
7518
+ return this.services.get("computerControl");
7519
+ }
7493
7520
  /**
7494
7521
  * The MCP-admin capability (enable/detach/list MCP servers), read by the
7495
7522
  * runner's mcp handlers + the desktop. @moxxy/plugin-mcp publishes it on the
@@ -7595,6 +7622,347 @@ var init_session = __esm({
7595
7622
  };
7596
7623
  }
7597
7624
  });
7625
+ function createWorkflowToolRunner(session, turnId, subagents) {
7626
+ return {
7627
+ get: (name) => session.tools.get(name),
7628
+ async execute(name, input, signal) {
7629
+ signal.throwIfAborted();
7630
+ const id = randomUUID();
7631
+ await session.log.append({
7632
+ type: "tool_call_requested",
7633
+ sessionId: session.id,
7634
+ turnId,
7635
+ source: "system",
7636
+ callId: asToolCallId(id),
7637
+ name,
7638
+ input
7639
+ });
7640
+ let output;
7641
+ let error;
7642
+ let received = false;
7643
+ const app = session.appContext();
7644
+ for await (const event of dispatchToolCall({
7645
+ sessionId: session.id,
7646
+ turnId,
7647
+ cwd: app.cwd,
7648
+ env: app.env,
7649
+ services: app.services,
7650
+ log: session.log,
7651
+ hooks: session.dispatcher,
7652
+ permissions: session.resolver,
7653
+ tools: session.tools,
7654
+ signal,
7655
+ subagents,
7656
+ emit: (event2) => session.log.append(event2)
7657
+ }, { id, name, input }, 0)) {
7658
+ if (event.type !== "tool_result" || event.callId !== id)
7659
+ continue;
7660
+ received = true;
7661
+ if (event.ok)
7662
+ output = event.output;
7663
+ else
7664
+ error = event.error?.message ?? "Workflow tool failed";
7665
+ }
7666
+ if (!received)
7667
+ throw new Error("Workflow tool outcome is unknown; action not retried");
7668
+ if (error)
7669
+ throw new Error(error);
7670
+ return output;
7671
+ }
7672
+ };
7673
+ }
7674
+ var init_workflow_tool_runner = __esm({
7675
+ "../core/dist/workflow-tool-runner.js"() {
7676
+ }
7677
+ });
7678
+ function approvalFingerprint(value2) {
7679
+ function canonical2(v) {
7680
+ if (Array.isArray(v))
7681
+ return v.map(canonical2);
7682
+ if (v && typeof v === "object")
7683
+ return Object.fromEntries(Object.entries(v).filter(([, item]) => item !== void 0).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => [key, canonical2(item)]));
7684
+ return v;
7685
+ }
7686
+ return createHash("sha256").update(JSON.stringify(canonical2(value2))).digest("hex");
7687
+ }
7688
+ function alive(pid) {
7689
+ try {
7690
+ process.kill(pid, 0);
7691
+ return true;
7692
+ } catch (error) {
7693
+ return error.code !== "ESRCH";
7694
+ }
7695
+ }
7696
+ function runKey(scope2) {
7697
+ const hash = approvalFingerprint([scope2.workflowId, scope2.runId]);
7698
+ return `${hash.slice(0, 8)}-${hash.slice(8, 12)}-4${hash.slice(13, 16)}-8${hash.slice(17, 20)}-${hash.slice(20, 32)}`;
7699
+ }
7700
+ var idSchema, choiceSchema, requestSchema, decisionSchema, markerSchema, WorkflowApprovals;
7701
+ var init_workflow_approvals = __esm({
7702
+ "../core/dist/permissions/workflow-approvals.js"() {
7703
+ idSchema = z.string().uuid();
7704
+ choiceSchema = z.enum(["allow_once", "allow_always", "deny"]);
7705
+ requestSchema = z.object({
7706
+ id: idSchema,
7707
+ workflowId: z.string().min(1),
7708
+ workflowName: z.string().min(1),
7709
+ revision: z.string().min(1),
7710
+ runId: z.string().min(1),
7711
+ tool: z.string().min(1),
7712
+ input: z.unknown(),
7713
+ fingerprint: z.string().length(64),
7714
+ createdAt: z.number().positive(),
7715
+ pid: z.number().int().positive()
7716
+ }).strict();
7717
+ decisionSchema = z.object({ choice: choiceSchema, createdAt: z.number().positive() }).strict();
7718
+ markerSchema = z.object({ createdAt: z.number().positive() }).strict();
7719
+ WorkflowApprovals = class {
7720
+ dir;
7721
+ calls = /* @__PURE__ */ new Map();
7722
+ receipts = /* @__PURE__ */ new Map();
7723
+ constructor(dir) {
7724
+ this.dir = dir;
7725
+ }
7726
+ file(kind, id) {
7727
+ return join(this.dir, kind, idSchema.parse(id) + ".json");
7728
+ }
7729
+ async read(kind, id, schema) {
7730
+ try {
7731
+ const raw = await readFile(this.file(kind, id), "utf8");
7732
+ if (Buffer.byteLength(raw) > 1048576)
7733
+ throw new Error("Approval record exceeds size limit");
7734
+ return schema.parse(JSON.parse(raw));
7735
+ } catch (error) {
7736
+ if (error.code === "ENOENT")
7737
+ return null;
7738
+ throw error;
7739
+ }
7740
+ }
7741
+ async publish(kind, id, value2) {
7742
+ const folder = join(this.dir, kind);
7743
+ await mkdir(folder, { recursive: true, mode: 448 });
7744
+ const target = this.file(kind, id);
7745
+ const temporary = join(folder, "." + randomUUID() + ".tmp");
7746
+ const json = JSON.stringify(value2);
7747
+ if (Buffer.byteLength(json) > 1048576)
7748
+ throw new Error("Approval record exceeds size limit");
7749
+ try {
7750
+ await writeFile(temporary, json, { mode: 384, flag: "wx" });
7751
+ await link(temporary, target);
7752
+ } finally {
7753
+ await unlink(temporary).catch(() => {
7754
+ });
7755
+ }
7756
+ }
7757
+ async requests() {
7758
+ let names;
7759
+ try {
7760
+ names = await readdir(join(this.dir, "requests"));
7761
+ } catch (error) {
7762
+ if (error.code === "ENOENT")
7763
+ return [];
7764
+ throw error;
7765
+ }
7766
+ const result = [];
7767
+ for (const name of names.filter((name2) => name2.endsWith(".json"))) {
7768
+ const request = await this.read("requests", name.slice(0, -5), requestSchema);
7769
+ if (request)
7770
+ result.push(request);
7771
+ }
7772
+ return result;
7773
+ }
7774
+ async list() {
7775
+ return Promise.all((await this.requests()).map(async (request) => {
7776
+ const decision = await this.read("decisions", request.id, decisionSchema);
7777
+ const revoked = await this.read("revoked", request.id, markerSchema);
7778
+ const cancelled = await this.read("cancelled", request.id, markerSchema) || await this.isCancelled(request);
7779
+ const status = revoked ? "revoked" : cancelled ? "cancelled" : decision ? decision.choice === "deny" ? "denied" : "allowed" : alive(request.pid) ? "pending" : "interrupted";
7780
+ const { pid: _pid, fingerprint: _fingerprint, ...item } = request;
7781
+ return {
7782
+ ...item,
7783
+ input: request.input,
7784
+ status,
7785
+ ...decision ? { choice: decision.choice } : {}
7786
+ };
7787
+ }));
7788
+ }
7789
+ async decide(id, choice) {
7790
+ choiceSchema.parse(choice);
7791
+ const item = (await this.list()).find((item2) => item2.id === idSchema.parse(id));
7792
+ if (!item || item.status !== "pending")
7793
+ throw new Error("Approval is no longer pending");
7794
+ await this.publish("decisions", id, { choice, createdAt: Date.now() });
7795
+ }
7796
+ async revoke(id) {
7797
+ const decision = await this.read("decisions", id, decisionSchema);
7798
+ if (decision?.choice !== "allow_always")
7799
+ throw new Error("No persistent approval to revoke");
7800
+ await this.publish("revoked", id, { createdAt: Date.now() });
7801
+ }
7802
+ async cancel(id) {
7803
+ const request = await this.read("requests", id, requestSchema);
7804
+ if (!request)
7805
+ throw new Error("Unknown approval");
7806
+ if (!await this.isCancelled(request)) {
7807
+ try {
7808
+ await this.publish("stopped-runs", runKey(request), { createdAt: Date.now() });
7809
+ } catch (error) {
7810
+ if (error.code !== "EEXIST")
7811
+ throw error;
7812
+ }
7813
+ }
7814
+ }
7815
+ async isCancelled(scope2) {
7816
+ return !!await this.read("stopped-runs", runKey(scope2), markerSchema);
7817
+ }
7818
+ async finishRun(runId) {
7819
+ for (const key of this.calls.keys())
7820
+ if (key.startsWith(runId + ":")) {
7821
+ this.calls.delete(key);
7822
+ this.receipts.delete(key);
7823
+ }
7824
+ for (const request of await this.requests()) {
7825
+ if (request.runId !== runId || await this.read("decisions", request.id, decisionSchema) || await this.read("cancelled", request.id, markerSchema))
7826
+ continue;
7827
+ await this.publish("cancelled", request.id, { createdAt: Date.now() });
7828
+ }
7829
+ }
7830
+ async check(scope2, call, signal, valid = async () => true) {
7831
+ const key = scope2.runId + ":" + approvalFingerprint([scope2, call]);
7832
+ let pending = this.calls.get(key);
7833
+ if (!pending) {
7834
+ pending = this.resolve(scope2, call, signal, valid, key);
7835
+ this.calls.set(key, pending);
7836
+ }
7837
+ const decision = await pending;
7838
+ const receipt = this.receipts.get(key);
7839
+ if (signal.aborted || await this.isCancelled(scope2) || !await valid() || receipt && await this.read("revoked", receipt, markerSchema)) {
7840
+ return { mode: "deny", reason: "Workflow approval revoked, changed or cancelled" };
7841
+ }
7842
+ return decision;
7843
+ }
7844
+ async resolve(scope2, call, signal, valid, key) {
7845
+ const deny = { mode: "deny", reason: "Workflow action denied or cancelled" };
7846
+ if (signal.aborted || await this.isCancelled(scope2) || !await valid())
7847
+ return deny;
7848
+ const fingerprint2 = approvalFingerprint({ name: call.name, input: call.input });
7849
+ for (const old of await this.requests()) {
7850
+ if (old.workflowId !== scope2.workflowId || old.revision !== scope2.revision || old.fingerprint !== fingerprint2)
7851
+ continue;
7852
+ const decision = await this.read("decisions", old.id, decisionSchema);
7853
+ if (decision?.choice === "deny" && old.runId === scope2.runId)
7854
+ return deny;
7855
+ if (decision?.choice === "allow_always" && await this.read("consumed", old.id, markerSchema) && !await this.read("revoked", old.id, markerSchema) && !await this.read("cancelled", old.id, markerSchema)) {
7856
+ this.receipts.set(key, old.id);
7857
+ return { mode: "allow" };
7858
+ }
7859
+ }
7860
+ const request = requestSchema.parse({
7861
+ ...scope2,
7862
+ id: randomUUID(),
7863
+ tool: call.name,
7864
+ input: call.input,
7865
+ fingerprint: fingerprint2,
7866
+ createdAt: Date.now(),
7867
+ pid: process.pid
7868
+ });
7869
+ await this.publish("requests", request.id, request);
7870
+ this.receipts.set(key, request.id);
7871
+ try {
7872
+ while (!signal.aborted && !await this.isCancelled(scope2) && await valid()) {
7873
+ const decision = await this.read("decisions", request.id, decisionSchema);
7874
+ if (decision) {
7875
+ if (signal.aborted || await this.isCancelled(scope2) || !await valid())
7876
+ break;
7877
+ await this.publish("consumed", request.id, { createdAt: Date.now() });
7878
+ return decision.choice === "deny" ? deny : { mode: "allow" };
7879
+ }
7880
+ await setTimeout$1(100, void 0, { signal });
7881
+ }
7882
+ } catch (error) {
7883
+ if (!signal.aborted)
7884
+ throw error;
7885
+ }
7886
+ await this.publish("cancelled", request.id, { createdAt: Date.now() });
7887
+ return deny;
7888
+ }
7889
+ };
7890
+ }
7891
+ });
7892
+ async function claimWorkflowLease(dir, workflowId, signal) {
7893
+ const folder = join(dir, createHash("sha256").update(workflowId).digest("hex"));
7894
+ await mkdir(folder, { recursive: true, mode: 448 });
7895
+ const own = { id: randomUUID(), pid: process.pid, ticket: 0 };
7896
+ const file = join(folder, own.id + ".json");
7897
+ const release = async () => {
7898
+ await unlink(file).catch((error) => {
7899
+ if (error.code !== "ENOENT")
7900
+ throw error;
7901
+ });
7902
+ };
7903
+ async function participants() {
7904
+ const all = [];
7905
+ for (const name of await readdir(folder)) {
7906
+ if (!name.endsWith(".json"))
7907
+ continue;
7908
+ z.string().uuid().parse(name.slice(0, -5));
7909
+ try {
7910
+ const raw = await readFile(join(folder, name), "utf8");
7911
+ if (raw.length > 2048)
7912
+ throw new Error("Invalid workflow lease");
7913
+ const ticket = ticketSchema.parse(JSON.parse(raw));
7914
+ if (ticket.id + ".json" !== name)
7915
+ throw new Error("Workflow lease identity mismatch");
7916
+ try {
7917
+ process.kill(ticket.pid, 0);
7918
+ } catch (error) {
7919
+ if (error.code === "ESRCH")
7920
+ continue;
7921
+ }
7922
+ all.push(ticket);
7923
+ } catch (error) {
7924
+ if (error.code !== "ENOENT")
7925
+ throw error;
7926
+ }
7927
+ }
7928
+ return all;
7929
+ }
7930
+ try {
7931
+ signal.throwIfAborted();
7932
+ await writeFileAtomic(file, JSON.stringify(own), { mode: 384 });
7933
+ own.ticket = Math.max(0, ...(await participants()).map((item) => item.ticket)) + 1;
7934
+ ticketSchema.parse(own);
7935
+ await writeFileAtomic(file, JSON.stringify(own), { mode: 384 });
7936
+ const deadline = Date.now() + 3e3;
7937
+ for (; ; ) {
7938
+ signal.throwIfAborted();
7939
+ const others = (await participants()).filter((item) => item.id !== own.id);
7940
+ if (others.some((item) => item.ticket === 0)) {
7941
+ if (Date.now() >= deadline)
7942
+ throw new Error("Workflow execution skipped: another runner is acquiring control");
7943
+ await setTimeout$1(10, void 0, { signal });
7944
+ continue;
7945
+ }
7946
+ if (others.some((item) => item.ticket < own.ticket || item.ticket === own.ticket && item.id < own.id)) {
7947
+ throw new Error("Workflow execution skipped: another execution is running or awaiting approval");
7948
+ }
7949
+ return release;
7950
+ }
7951
+ } catch (error) {
7952
+ await release();
7953
+ throw error;
7954
+ }
7955
+ }
7956
+ var ticketSchema;
7957
+ var init_workflow_lease = __esm({
7958
+ "../core/dist/permissions/workflow-lease.js"() {
7959
+ ticketSchema = z.object({
7960
+ id: z.string().uuid(),
7961
+ pid: z.number().int().positive(),
7962
+ ticket: z.number().int().nonnegative().safe()
7963
+ }).strict();
7964
+ }
7965
+ });
7598
7966
 
7599
7967
  // ../core/dist/setup-agent.js
7600
7968
  function resolvePermissions(p) {
@@ -7869,7 +8237,7 @@ async function discoverSkills(opts = {}) {
7869
8237
  }
7870
8238
  return [...seenNames.values()];
7871
8239
  }
7872
- async function loadDir(dir, scope, logger, depth = 0) {
8240
+ async function loadDir(dir, scope2, logger, depth = 0) {
7873
8241
  let entries;
7874
8242
  try {
7875
8243
  entries = await promises.readdir(dir, { withFileTypes: true });
@@ -7886,7 +8254,7 @@ async function loadDir(dir, scope, logger, depth = 0) {
7886
8254
  });
7887
8255
  continue;
7888
8256
  }
7889
- out.push(...await loadDir(path3.join(dir, entry.name), scope, logger, depth + 1));
8257
+ out.push(...await loadDir(path3.join(dir, entry.name), scope2, logger, depth + 1));
7890
8258
  continue;
7891
8259
  }
7892
8260
  if (!entry.isFile() || !entry.name.endsWith(".md"))
@@ -7911,9 +8279,9 @@ async function loadDir(dir, scope, logger, depth = 0) {
7911
8279
  const fm = parsed.data;
7912
8280
  const finalTriggers = fm.triggers && fm.triggers.length > 0 ? fm.triggers : deriveTriggers(fm.name);
7913
8281
  out.push({
7914
- id: asSkillId(`${scope}/${fm.name}`),
8282
+ id: asSkillId(`${scope2}/${fm.name}`),
7915
8283
  path: full,
7916
- scope,
8284
+ scope: scope2,
7917
8285
  frontmatter: { ...fm, triggers: finalTriggers },
7918
8286
  body: body.trimEnd()
7919
8287
  });
@@ -7979,11 +8347,11 @@ var init_synthesize_draft = __esm({
7979
8347
  The body is the instructions for future invocations. Keep it under 30 lines. Numbered steps preferred.`;
7980
8348
  }
7981
8349
  });
7982
- async function synthesizeSkill(session, intent, scope, opts = {}, turnId) {
8350
+ async function synthesizeSkill(session, intent, scope2, opts = {}, turnId) {
7983
8351
  const provider = session.providers.getActive();
7984
8352
  const model = opts.model ?? session.lastResolvedModel ?? provider.models[0]?.id ?? "default";
7985
8353
  const draft = await draftSkill(provider, model, intent, session.signal);
7986
- const baseDir = scope === "project" ? opts.projectDir ?? defaultProjectSkillsDir(session.cwd) : opts.userDir ?? defaultUserSkillsDir();
8354
+ const baseDir = scope2 === "project" ? opts.projectDir ?? defaultProjectSkillsDir(session.cwd) : opts.userDir ?? defaultUserSkillsDir();
7987
8355
  await promises.mkdir(baseDir, { recursive: true });
7988
8356
  const parsed = skillFrontmatterSchema.safeParse(draft.frontmatter);
7989
8357
  if (!parsed.success) {
@@ -7994,9 +8362,9 @@ async function synthesizeSkill(session, intent, scope, opts = {}, turnId) {
7994
8362
  const finalPath = await writeUniqueSkill(baseDir, slugify(frontmatter.name), draft.raw);
7995
8363
  const basename8 = path3.basename(finalPath, ".md");
7996
8364
  const skill = {
7997
- id: asSkillId(`${scope}/${basename8}`),
8365
+ id: asSkillId(`${scope2}/${basename8}`),
7998
8366
  path: finalPath,
7999
- scope,
8367
+ scope: scope2,
8000
8368
  frontmatter,
8001
8369
  body: draft.body.trimEnd()
8002
8370
  };
@@ -8010,7 +8378,7 @@ async function synthesizeSkill(session, intent, scope, opts = {}, turnId) {
8010
8378
  skillId: skill.id,
8011
8379
  name: skill.frontmatter.name,
8012
8380
  path: finalPath,
8013
- scope,
8381
+ scope: scope2,
8014
8382
  originatingPrompt: intent
8015
8383
  });
8016
8384
  } catch (err) {
@@ -8024,13 +8392,13 @@ async function synthesizeSkill(session, intent, scope, opts = {}, turnId) {
8024
8392
  ts: (/* @__PURE__ */ new Date()).toISOString(),
8025
8393
  sessionId: String(session.id),
8026
8394
  originatingPrompt: intent,
8027
- scope
8395
+ scope: scope2
8028
8396
  });
8029
8397
  } catch (err) {
8030
8398
  process.stderr.write(`moxxy: synthesize_skill audit append failed (${auditPath}): ${err instanceof Error ? err.message : String(err)}
8031
8399
  `);
8032
8400
  }
8033
- return { skill, path: finalPath, scope };
8401
+ return { skill, path: finalPath, scope: scope2 };
8034
8402
  }
8035
8403
  function slugify(name) {
8036
8404
  return name.toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60);
@@ -8101,8 +8469,8 @@ function buildSynthesizeSkillPlugin(session, opts = {}) {
8101
8469
  timeMs: 12e4
8102
8470
  }
8103
8471
  },
8104
- handler: async ({ intent, scope }, ctx) => {
8105
- const result = await synthesizeSkill(session, intent, scope, opts, ctx.turnId);
8472
+ handler: async ({ intent, scope: scope2 }, ctx) => {
8473
+ const result = await synthesizeSkill(session, intent, scope2, opts, ctx.turnId);
8106
8474
  return {
8107
8475
  path: result.path,
8108
8476
  scope: result.scope,
@@ -8644,7 +9012,7 @@ var require_jiti = __commonJS({
8644
9012
  function V2() {
8645
9013
  return 10 !== n2.getToken() ? (k2(3, [], [2, 5]), false) : (P2(false), 6 === n2.getToken() ? (I3(":"), T2(), U3() || k2(4, [], [2, 5])) : k2(5, [], [2, 5]), a2.pop(), true);
8646
9014
  }
8647
- function z63() {
9015
+ function z68() {
8648
9016
  l2(), T2();
8649
9017
  let e5 = false;
8650
9018
  for (; 2 !== n2.getToken() && 17 !== n2.getToken(); ) {
@@ -8671,14 +9039,14 @@ var require_jiti = __commonJS({
8671
9039
  case 3:
8672
9040
  return G2();
8673
9041
  case 1:
8674
- return z63();
9042
+ return z68();
8675
9043
  case 10:
8676
9044
  return P2(true);
8677
9045
  default:
8678
9046
  return J3();
8679
9047
  }
8680
9048
  }
8681
- return r(T2, "scanNext"), r(k2, "handleError"), r(P2, "parseString"), r(J3, "parseLiteral"), r(V2, "parseProperty"), r(z63, "parseObject"), r(G2, "parseArray"), r(U3, "parseValue"), T2(), 17 === n2.getToken() ? !!i3.allowEmptyContent || (k2(4, [], []), false) : U3() ? (17 !== n2.getToken() && k2(9, [], []), true) : (k2(4, [], []), false);
9049
+ return r(T2, "scanNext"), r(k2, "handleError"), r(P2, "parseString"), r(J3, "parseLiteral"), r(V2, "parseProperty"), r(z68, "parseObject"), r(G2, "parseArray"), r(U3, "parseValue"), T2(), 17 === n2.getToken() ? !!i3.allowEmptyContent || (k2(4, [], []), false) : U3() ? (17 !== n2.getToken() && k2(9, [], []), true) : (k2(4, [], []), false);
8682
9050
  }
8683
9051
  new Array(W3).fill(0).map((e4, t3) => "\n" + " ".repeat(t3)), new Array(W3).fill(0).map((e4, t3) => "\r" + " ".repeat(t3)), new Array(W3).fill(0).map((e4, t3) => "\r\n" + " ".repeat(t3)), new Array(W3).fill(0).map((e4, t3) => "\n" + " ".repeat(t3)), new Array(W3).fill(0).map((e4, t3) => "\r" + " ".repeat(t3)), new Array(W3).fill(0).map((e4, t3) => "\r\n" + " ".repeat(t3)), (function(e4) {
8684
9052
  e4.DEFAULT = { allowTrailingComma: false };
@@ -12584,13 +12952,16 @@ __export(dist_exports, {
12584
12952
  TranscriberRegistry: () => TranscriberRegistry,
12585
12953
  TunnelProviderRegistry: () => TunnelProviderRegistry,
12586
12954
  ViewRendererRegistry: () => ViewRendererRegistry,
12955
+ WorkflowApprovals: () => WorkflowApprovals,
12587
12956
  appendAuditRecord: () => appendAuditRecord,
12957
+ approvalFingerprint: () => approvalFingerprint,
12588
12958
  attachAuditSink: () => attachAuditSink,
12589
12959
  auditDir: () => auditDir,
12590
12960
  auditFileFor: () => auditFileFor,
12591
12961
  autoAllowResolver: () => autoAllowResolver,
12592
12962
  buildSynthesizeSkillPlugin: () => buildSynthesizeSkillPlugin,
12593
12963
  chainRecord: () => chainRecord,
12964
+ claimWorkflowLease: () => claimWorkflowLease,
12594
12965
  clearRetainedChildren: () => clearRetainedChildren,
12595
12966
  clearUsageStats: () => clearUsageStats,
12596
12967
  collectTurn: () => collectTurn,
@@ -12601,6 +12972,7 @@ __export(dist_exports, {
12601
12972
  createLogger: () => createLogger,
12602
12973
  createPluginLoader: () => createPluginLoader,
12603
12974
  createSubagentSpawner: () => createSubagentSpawner,
12975
+ createWorkflowToolRunner: () => createWorkflowToolRunner,
12604
12976
  defaultProjectSkillsDir: () => defaultProjectSkillsDir,
12605
12977
  defaultSessionsDir: () => defaultSessionsDir,
12606
12978
  defaultUserSkillsDir: () => defaultUserSkillsDir,
@@ -12650,11 +13022,16 @@ __export(dist_exports, {
12650
13022
  usageStatsPath: () => usageStatsPath,
12651
13023
  validateDoc: () => validateDoc,
12652
13024
  verifyAuditDay: () => verifyAuditDay,
12653
- verifyChain: () => verifyChain
13025
+ verifyChain: () => verifyChain,
13026
+ withPermissionScope: () => withPermissionScope
12654
13027
  });
12655
13028
  var init_dist2 = __esm({
12656
13029
  "../core/dist/index.js"() {
12657
13030
  init_session();
13031
+ init_workflow_tool_runner();
13032
+ init_workflow_approvals();
13033
+ init_scope();
13034
+ init_workflow_lease();
12658
13035
  init_run_turn();
12659
13036
  init_setup_agent();
12660
13037
  init_subagents();
@@ -13239,7 +13616,7 @@ function withoutPath(obj, segments) {
13239
13616
  return Object.keys(child).length === 0 ? [] : [[key, child]];
13240
13617
  }));
13241
13618
  }
13242
- function stripLockedKeys(config, locked, scope) {
13619
+ function stripLockedKeys(config, locked, scope2) {
13243
13620
  if (locked.length === 0)
13244
13621
  return { config, overrides: [] };
13245
13622
  let clone = structuredClone(config);
@@ -13250,7 +13627,7 @@ function stripLockedKeys(config, locked, scope) {
13250
13627
  continue;
13251
13628
  if (!hasPath(clone, segments))
13252
13629
  continue;
13253
- overrides.push({ key, scope });
13630
+ overrides.push({ key, scope: scope2 });
13254
13631
  clone = withoutPath(clone, segments);
13255
13632
  }
13256
13633
  return { config: clone, overrides };
@@ -20697,8 +21074,8 @@ var init_loader3 = __esm({
20697
21074
  cachedJiti = /* @__PURE__ */ new Map();
20698
21075
  }
20699
21076
  });
20700
- async function findScopePath(scope, cwd2) {
20701
- if (scope === "user") {
21077
+ async function findScopePath(scope2, cwd2) {
21078
+ if (scope2 === "user") {
20702
21079
  const yaml = USER_YAML();
20703
21080
  try {
20704
21081
  await promises.access(yaml);
@@ -20709,8 +21086,8 @@ async function findScopePath(scope, cwd2) {
20709
21086
  }
20710
21087
  return findUpward(cwd2, PROJECT_YAML_NAMES);
20711
21088
  }
20712
- function scopeDefaultPath(scope, cwd2) {
20713
- return scope === "user" ? USER_YAML() : path3.join(cwd2, "moxxy.config.yaml");
21089
+ function scopeDefaultPath(scope2, cwd2) {
21090
+ return scope2 === "user" ? USER_YAML() : path3.join(cwd2, "moxxy.config.yaml");
20714
21091
  }
20715
21092
  function parseDotPath(p) {
20716
21093
  return p.split(".").map((seg) => /^\d+$/.test(seg) ? Number(seg) : seg);
@@ -20748,8 +21125,8 @@ var init_config_writer = __esm({
20748
21125
  configWriteMutex = createMutex();
20749
21126
  }
20750
21127
  });
20751
- async function findScopePath2(scope, cwd2) {
20752
- if (scope === "user") {
21128
+ async function findScopePath2(scope2, cwd2) {
21129
+ if (scope2 === "user") {
20753
21130
  const yaml = USER_YAML2();
20754
21131
  try {
20755
21132
  await promises.access(yaml);
@@ -20760,8 +21137,8 @@ async function findScopePath2(scope, cwd2) {
20760
21137
  }
20761
21138
  return findUpward(cwd2, PROJECT_YAML_NAMES2);
20762
21139
  }
20763
- function scopeDefaultPath2(scope, cwd2) {
20764
- return scope === "user" ? USER_YAML2() : path3.join(cwd2, "moxxy.config.yaml");
21140
+ function scopeDefaultPath2(scope2, cwd2) {
21141
+ return scope2 === "user" ? USER_YAML2() : path3.join(cwd2, "moxxy.config.yaml");
20765
21142
  }
20766
21143
  function isOutsideCwd(target, cwd2) {
20767
21144
  const rel = path3.relative(path3.resolve(cwd2), path3.resolve(target));
@@ -20805,9 +21182,9 @@ function buildConfigPlugin(opts = { cwd: process.cwd() }) {
20805
21182
  timeMs: 1e4
20806
21183
  }
20807
21184
  },
20808
- handler: async ({ scope }) => {
20809
- const found = await findScopePath2(scope, cwd2);
20810
- return { scope, path: found, defaultPath: scopeDefaultPath2(scope, cwd2) };
21185
+ handler: async ({ scope: scope2 }) => {
21186
+ const found = await findScopePath2(scope2, cwd2);
21187
+ return { scope: scope2, path: found, defaultPath: scopeDefaultPath2(scope2, cwd2) };
20811
21188
  }
20812
21189
  }),
20813
21190
  defineTool({
@@ -20821,12 +21198,12 @@ function buildConfigPlugin(opts = { cwd: process.cwd() }) {
20821
21198
  timeMs: 1e4
20822
21199
  }
20823
21200
  },
20824
- handler: async ({ scope }) => {
20825
- const found = await findScopePath2(scope, cwd2);
21201
+ handler: async ({ scope: scope2 }) => {
21202
+ const found = await findScopePath2(scope2, cwd2);
20826
21203
  if (!found)
20827
- return { scope, path: null, text: "" };
21204
+ return { scope: scope2, path: null, text: "" };
20828
21205
  const text2 = await promises.readFile(found, "utf8");
20829
- return { scope, path: found, text: text2 };
21206
+ return { scope: scope2, path: found, text: text2 };
20830
21207
  }
20831
21208
  }),
20832
21209
  defineTool({
@@ -20844,8 +21221,8 @@ function buildConfigPlugin(opts = { cwd: process.cwd() }) {
20844
21221
  timeMs: 1e4
20845
21222
  }
20846
21223
  },
20847
- handler: async ({ scope, path: dotPath }) => {
20848
- const found = await findScopePath2(scope, cwd2);
21224
+ handler: async ({ scope: scope2, path: dotPath }) => {
21225
+ const found = await findScopePath2(scope2, cwd2);
20849
21226
  if (!found)
20850
21227
  return null;
20851
21228
  const yamlMod = await Promise.resolve().then(() => __toESM(require_dist()));
@@ -20881,9 +21258,9 @@ function buildConfigPlugin(opts = { cwd: process.cwd() }) {
20881
21258
  timeMs: 3e4
20882
21259
  }
20883
21260
  },
20884
- handler: async ({ scope, path: dotPath, value: value2 }) => {
21261
+ handler: async ({ scope: scope2, path: dotPath, value: value2 }) => {
20885
21262
  const written = await setConfigValue({
20886
- scope,
21263
+ scope: scope2,
20887
21264
  cwd: cwd2,
20888
21265
  path: dotPath,
20889
21266
  value: parseValue(value2)
@@ -20901,7 +21278,7 @@ function buildConfigPlugin(opts = { cwd: process.cwd() }) {
20901
21278
  }
20902
21279
  return {
20903
21280
  path: written.path,
20904
- outsideCwd: scope === "project" && isOutsideCwd(written.path, cwd2),
21281
+ outsideCwd: scope2 === "project" && isOutsideCwd(written.path, cwd2),
20905
21282
  runtime
20906
21283
  };
20907
21284
  }
@@ -20946,18 +21323,18 @@ function buildConfigPlugin(opts = { cwd: process.cwd() }) {
20946
21323
  timeMs: 3e4
20947
21324
  }
20948
21325
  },
20949
- handler: async ({ scope }) => writeMutex2.run(async () => {
20950
- const existing = await findScopePath2(scope, cwd2);
21326
+ handler: async ({ scope: scope2 }) => writeMutex2.run(async () => {
21327
+ const existing = await findScopePath2(scope2, cwd2);
20951
21328
  if (existing) {
20952
21329
  return {
20953
21330
  path: existing,
20954
21331
  created: false,
20955
- outsideCwd: scope === "project" && isOutsideCwd(existing, cwd2)
21332
+ outsideCwd: scope2 === "project" && isOutsideCwd(existing, cwd2)
20956
21333
  };
20957
21334
  }
20958
- const target = scopeDefaultPath2(scope, cwd2);
21335
+ const target = scopeDefaultPath2(scope2, cwd2);
20959
21336
  await promises.mkdir(path3.dirname(target), { recursive: true });
20960
- const template = `# moxxy config (${scope} scope)
21337
+ const template = `# moxxy config (${scope2} scope)
20961
21338
  # Documentation: https://docs.moxxy.ai
20962
21339
  plugins:
20963
21340
  provider:
@@ -20972,7 +21349,7 @@ plugins:
20972
21349
  return {
20973
21350
  path: target,
20974
21351
  created: true,
20975
- outsideCwd: scope === "project" && isOutsideCwd(target, cwd2)
21352
+ outsideCwd: scope2 === "project" && isOutsideCwd(target, cwd2)
20976
21353
  };
20977
21354
  })
20978
21355
  }),
@@ -24389,7 +24766,7 @@ async function writeInbox(entry, result, opts = {}) {
24389
24766
  `firedAt: ${(/* @__PURE__ */ new Date()).toISOString()}`,
24390
24767
  entry.cron ? `cron: "${entry.cron}"` : `runAt: ${entry.runAt}`,
24391
24768
  entry.channel ? `channel: ${entry.channel}` : null,
24392
- `outcome: ${result.error ? "error" : "ok"}`,
24769
+ `outcome: ${result.cancelled ? "cancelled" : result.error ? "error" : "ok"}`,
24393
24770
  `---`,
24394
24771
  ""
24395
24772
  ].filter((line) => line !== null).join("\n");
@@ -24400,10 +24777,34 @@ ${result.text}` : result.text;
24400
24777
  return file;
24401
24778
  }
24402
24779
  async function runSchedule(entry, runner, store, inboxOpts = {}) {
24780
+ if (entry.source === "workflow")
24781
+ await store.update(entry.id, { lastStartedAt: Date.now() });
24782
+ const controller = new AbortController();
24783
+ let checking = false;
24784
+ const checkSchedule = async () => {
24785
+ store.invalidate();
24786
+ const current = await store.get(entry.id);
24787
+ if (!current?.enabled)
24788
+ controller.abort("Workflow schedule disabled or deleted");
24789
+ };
24790
+ const monitor = entry.source === "workflow" ? setInterval(() => {
24791
+ if (checking)
24792
+ return;
24793
+ checking = true;
24794
+ void checkSchedule().catch((error) => controller.abort(error)).finally(() => {
24795
+ checking = false;
24796
+ });
24797
+ }, 200) : void 0;
24798
+ monitor?.unref();
24403
24799
  let result;
24404
24800
  try {
24801
+ if (entry.source === "workflow") {
24802
+ await checkSchedule();
24803
+ controller.signal.throwIfAborted();
24804
+ }
24405
24805
  result = await runner.runPrompt({
24406
24806
  prompt: entry.prompt,
24807
+ ...entry.source === "workflow" ? { signal: controller.signal } : {},
24407
24808
  ...entry.model ? { model: entry.model } : {},
24408
24809
  scheduleName: entry.name,
24409
24810
  // A workflow-mirror row (source='workflow') reads as "Workflow ran";
@@ -24411,10 +24812,12 @@ async function runSchedule(entry, runner, store, inboxOpts = {}) {
24411
24812
  origin: entry.source === "workflow" && entry.workflowName ? { kind: "workflow", name: entry.workflowName } : { kind: "schedule", name: entry.name }
24412
24813
  });
24413
24814
  } catch (err) {
24414
- result = {
24815
+ result = controller.signal.aborted ? { text: "", cancelled: true } : {
24415
24816
  text: "",
24416
24817
  error: err instanceof Error ? err.message : String(err)
24417
24818
  };
24819
+ } finally {
24820
+ clearInterval(monitor);
24418
24821
  }
24419
24822
  let inboxPath;
24420
24823
  try {
@@ -24425,13 +24828,14 @@ async function runSchedule(entry, runner, store, inboxOpts = {}) {
24425
24828
  const isOneShot = !!entry.runAt && !entry.cron;
24426
24829
  const patch = {
24427
24830
  lastRunAt: now,
24428
- lastResult: result.error ? "error" : "ok",
24831
+ lastResult: result.cancelled ? "cancelled" : result.error ? "error" : "ok",
24429
24832
  ...result.error ? { lastError: result.error.slice(0, 500) } : { lastError: void 0 },
24430
24833
  ...isOneShot ? { enabled: false } : {}
24431
24834
  };
24432
24835
  await store.update(entry.id, patch);
24433
24836
  return {
24434
- ok: !result.error,
24837
+ ok: !result.cancelled && !result.error,
24838
+ ...result.cancelled ? { cancelled: true } : {},
24435
24839
  text: result.text,
24436
24840
  ...result.error ? { error: result.error } : {},
24437
24841
  ...inboxPath ? { inboxPath } : {}
@@ -24489,7 +24893,8 @@ var init_skill_sync = __esm({
24489
24893
 
24490
24894
  // ../plugin-scheduler/dist/poller.js
24491
24895
  function cronBaseline(entry) {
24492
- return entry.lastRunAt ?? entry.createdAt;
24896
+ const baseline = entry.lastRunAt ?? entry.createdAt;
24897
+ return Math.max(baseline, entry.timingChangedAt ?? baseline, entry.lastStartedAt ?? baseline, entry.lastSkippedAt ?? baseline);
24493
24898
  }
24494
24899
  function nextCronFire(entry) {
24495
24900
  if (!entry.cron)
@@ -24509,6 +24914,8 @@ function isDue(entry, now) {
24509
24914
  if (!entry.enabled)
24510
24915
  return false;
24511
24916
  if (entry.runAt && !entry.cron) {
24917
+ if (entry.source === "workflow" && (entry.lastStartedAt ?? 0) >= entry.runAt)
24918
+ return false;
24512
24919
  return entry.runAt <= now;
24513
24920
  }
24514
24921
  if (!entry.cron)
@@ -24528,6 +24935,7 @@ var init_poller = __esm({
24528
24935
  NEXT_FIRE_CACHE_MAX = 4096;
24529
24936
  SchedulerPoller = class _SchedulerPoller {
24530
24937
  opts;
24938
+ activeWorkflows = /* @__PURE__ */ new Map();
24531
24939
  timer = null;
24532
24940
  running = false;
24533
24941
  tickPromise = Promise.resolve();
@@ -24564,6 +24972,7 @@ var init_poller = __esm({
24564
24972
  this.timer = null;
24565
24973
  }
24566
24974
  await this.tickPromise.catch(() => void 0);
24975
+ await Promise.allSettled(this.activeWorkflows.values());
24567
24976
  }
24568
24977
  /** Fire any due schedules right now, ignoring the timer cadence.
24569
24978
  * Returns the number of due schedules that were attempted — counted at the
@@ -24626,6 +25035,15 @@ var init_poller = __esm({
24626
25035
  }
24627
25036
  if (!due)
24628
25037
  continue;
25038
+ if (entry.source === "workflow" && this.activeWorkflows.has(entry.id)) {
25039
+ await this.opts.store.update(entry.id, {
25040
+ lastSkippedAt: now,
25041
+ lastSkipReason: "Previous workflow execution is still running or awaiting approval"
25042
+ });
25043
+ continue;
25044
+ }
25045
+ if (entry.source === "workflow" && this.activeWorkflows.size >= 4)
25046
+ continue;
24629
25047
  if (entry.ownerSessionId !== void 0 && this.opts.ownerSessionId !== void 0 && entry.ownerSessionId !== this.opts.ownerSessionId) {
24630
25048
  continue;
24631
25049
  }
@@ -24655,26 +25073,35 @@ var init_poller = __esm({
24655
25073
  attempted += 1;
24656
25074
  if (fireKey !== null)
24657
25075
  this.rememberFired(fireKey);
24658
- try {
24659
- const outcome = await (this.opts.firingLock ? this.opts.firingLock.run(entry.id, () => runSchedule(entry, this.opts.runner, this.opts.store, this.opts.inbox)) : runSchedule(entry, this.opts.runner, this.opts.store, this.opts.inbox));
24660
- const log = this.opts.logger;
24661
- if (log?.info) {
24662
- log.info("scheduler: fired", {
24663
- schedule: entry.name,
24664
- ok: outcome.ok,
24665
- inbox: outcome.inboxPath
24666
- });
24667
- }
24668
- onFired?.(entry, { ok: outcome.ok, text: outcome.text });
24669
- } catch (err) {
24670
- const log = this.opts.logger;
24671
- if (log?.error) {
24672
- log.error("scheduler: run failed", {
24673
- schedule: entry.name,
24674
- err: err instanceof Error ? err.message : String(err)
24675
- });
25076
+ const fire = async () => {
25077
+ try {
25078
+ const outcome = await (this.opts.firingLock ? this.opts.firingLock.run(entry.id, () => runSchedule(entry, this.opts.runner, this.opts.store, this.opts.inbox)) : runSchedule(entry, this.opts.runner, this.opts.store, this.opts.inbox));
25079
+ const log = this.opts.logger;
25080
+ if (log?.info) {
25081
+ log.info("scheduler: fired", {
25082
+ schedule: entry.name,
25083
+ ok: outcome.ok,
25084
+ inbox: outcome.inboxPath
25085
+ });
25086
+ }
25087
+ onFired?.(entry, { ok: outcome.ok, text: outcome.text });
25088
+ } catch (err) {
25089
+ const log = this.opts.logger;
25090
+ if (log?.error) {
25091
+ log.error("scheduler: run failed", {
25092
+ schedule: entry.name,
25093
+ err: err instanceof Error ? err.message : String(err)
25094
+ });
25095
+ }
24676
25096
  }
24677
- }
25097
+ };
25098
+ if (entry.source === "workflow") {
25099
+ const running = fire().finally(() => {
25100
+ this.activeWorkflows.delete(entry.id);
25101
+ });
25102
+ this.activeWorkflows.set(entry.id, running);
25103
+ } else
25104
+ await fire();
24678
25105
  }
24679
25106
  if (this.opts.fireLock) {
24680
25107
  await this.opts.fireLock.sweep(now).catch(() => void 0);
@@ -24708,6 +25135,15 @@ var init_poller = __esm({
24708
25135
  function defaultSchedulesFile() {
24709
25136
  return moxxyPath("schedules.json");
24710
25137
  }
25138
+ function repairWorkflowDate(entry, now) {
25139
+ if (entry.source !== "workflow" || entry.createdAt > 0)
25140
+ return entry;
25141
+ return scheduleEntrySchema.parse({
25142
+ ...entry,
25143
+ createdAt: entry.lastRunAt && entry.lastRunAt > 0 ? entry.lastRunAt : now,
25144
+ migratedAt: now
25145
+ });
25146
+ }
24711
25147
  function isVisibleSchedule(entry) {
24712
25148
  return entry.deletedAt === void 0;
24713
25149
  }
@@ -24733,8 +25169,15 @@ var init_store2 = __esm({
24733
25169
  model: z.string().optional(),
24734
25170
  enabled: z.boolean().default(true),
24735
25171
  createdAt: z.number().int(),
25172
+ /** New timing definition starts here without overwriting run history. */
25173
+ timingChangedAt: z.number().int().positive().optional(),
25174
+ /** Audit marker for the legacy workflow createdAt=0 repair. */
25175
+ migratedAt: z.number().int().positive().optional(),
24736
25176
  lastRunAt: z.number().int().optional(),
24737
- lastResult: z.enum(["ok", "error"]).optional(),
25177
+ lastStartedAt: z.number().int().positive().optional(),
25178
+ lastSkippedAt: z.number().int().positive().optional(),
25179
+ lastSkipReason: z.string().optional(),
25180
+ lastResult: z.enum(["ok", "error", "cancelled"]).optional(),
24738
25181
  lastError: z.string().optional(),
24739
25182
  source: scheduleSourceSchema.default("manual"),
24740
25183
  /**
@@ -24784,7 +25227,9 @@ var init_store2 = __esm({
24784
25227
  // file is quarantined (renamed to `<file>.corrupt-<ts>`) and the store resets
24785
25228
  // to empty so the data loss is observable; an unreadable file resets to empty.
24786
25229
  store;
25230
+ now;
24787
25231
  constructor(opts = {}) {
25232
+ this.now = opts.now ?? Date.now;
24788
25233
  const file = opts.file ?? defaultSchedulesFile();
24789
25234
  const logger = opts.logger;
24790
25235
  this.store = createJsonFileStore({
@@ -24841,9 +25286,11 @@ var init_store2 = __esm({
24841
25286
  this.store.invalidate();
24842
25287
  }
24843
25288
  async list() {
25289
+ await this.migrateWorkflowDates();
24844
25290
  return (await this.store.read()).filter(isVisibleSchedule);
24845
25291
  }
24846
25292
  async get(id) {
25293
+ await this.migrateWorkflowDates();
24847
25294
  const entry = await this.store.get(id);
24848
25295
  return entry && isVisibleSchedule(entry) ? entry : null;
24849
25296
  }
@@ -25000,19 +25447,43 @@ var init_store2 = __esm({
25000
25447
  */
25001
25448
  async syncWorkflowSchedule(workflowName2, entry) {
25002
25449
  await this.store.mutate((schedules) => {
25450
+ const now = this.now();
25451
+ const current = schedules.find((s) => s.source === "workflow" && s.workflowName === workflowName2);
25003
25452
  const existingDeleted = schedules.find((s) => s.source === "workflow" && s.workflowName === workflowName2 && !isVisibleSchedule(s));
25004
25453
  const filtered = schedules.filter((s) => !(s.source === "workflow" && s.workflowName === workflowName2));
25005
25454
  if (entry) {
25006
- filtered.push(existingDeleted ?? scheduleEntrySchema.parse({
25455
+ const timingChanged = current && (current.cron !== entry.cron || current.runAt !== entry.runAt || current.timeZone !== entry.timeZone);
25456
+ const merged = scheduleEntrySchema.parse({
25007
25457
  ...entry,
25008
- id: entry.id || ulid(),
25458
+ id: current?.id ?? (entry.id || ulid()),
25459
+ createdAt: current?.createdAt ?? (entry.createdAt > 0 ? entry.createdAt : now),
25460
+ enabled: current?.enabled ?? entry.enabled,
25461
+ ...current ? {
25462
+ lastRunAt: current.lastRunAt,
25463
+ lastStartedAt: current.lastStartedAt,
25464
+ lastSkippedAt: current.lastSkippedAt,
25465
+ lastSkipReason: current.lastSkipReason,
25466
+ lastResult: current.lastResult,
25467
+ lastError: current.lastError,
25468
+ migratedAt: current.migratedAt,
25469
+ timingChangedAt: timingChanged ? now : current.timingChangedAt
25470
+ } : {},
25009
25471
  source: "workflow",
25010
25472
  workflowName: workflowName2
25011
- }));
25473
+ });
25474
+ filtered.push(repairWorkflowDate(existingDeleted ?? merged, now));
25475
+ } else if (existingDeleted) {
25476
+ filtered.push(existingDeleted);
25012
25477
  }
25013
25478
  return filtered;
25014
25479
  });
25015
25480
  }
25481
+ async migrateWorkflowDates() {
25482
+ const rows = await this.store.read();
25483
+ if (!rows.some((entry) => entry.source === "workflow" && entry.createdAt <= 0))
25484
+ return;
25485
+ await this.store.mutate((entries) => entries.map((entry) => repairWorkflowDate(entry, this.now())));
25486
+ }
25016
25487
  };
25017
25488
  }
25018
25489
  });
@@ -25041,6 +25512,9 @@ function describeScheduleEntry(entry) {
25041
25512
  targetSessionId: entry.ownerSessionId ?? null,
25042
25513
  createdAt: entry.createdAt,
25043
25514
  lastRunAt: entry.lastRunAt ?? null,
25515
+ lastStartedAt: entry.lastStartedAt ?? null,
25516
+ lastSkippedAt: entry.lastSkippedAt ?? null,
25517
+ lastSkipReason: entry.lastSkipReason ?? null,
25044
25518
  lastResult: entry.lastResult ?? null,
25045
25519
  lastError: entry.lastError ?? null,
25046
25520
  nextFireAt,
@@ -32445,7 +32919,7 @@ var require_websocket = __commonJS({
32445
32919
  var http = __require("http");
32446
32920
  var net3 = __require("net");
32447
32921
  var tls = __require("tls");
32448
- var { randomBytes: randomBytes8, createHash: createHash8 } = __require("crypto");
32922
+ var { randomBytes: randomBytes8, createHash: createHash10 } = __require("crypto");
32449
32923
  var { Duplex, Readable } = __require("stream");
32450
32924
  var { URL: URL2 } = __require("url");
32451
32925
  var PerMessageDeflate2 = require_permessage_deflate();
@@ -33113,7 +33587,7 @@ var require_websocket = __commonJS({
33113
33587
  abortHandshake(websocket, socket, "Invalid Upgrade header");
33114
33588
  return;
33115
33589
  }
33116
- const digest = createHash8("sha1").update(key + GUID).digest("base64");
33590
+ const digest = createHash10("sha1").update(key + GUID).digest("base64");
33117
33591
  if (res.headers["sec-websocket-accept"] !== digest) {
33118
33592
  abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
33119
33593
  return;
@@ -33479,7 +33953,7 @@ var require_websocket_server = __commonJS({
33479
33953
  var EventEmitter3 = __require("events");
33480
33954
  var http = __require("http");
33481
33955
  var { Duplex } = __require("stream");
33482
- var { createHash: createHash8 } = __require("crypto");
33956
+ var { createHash: createHash10 } = __require("crypto");
33483
33957
  var extension2 = require_extension();
33484
33958
  var PerMessageDeflate2 = require_permessage_deflate();
33485
33959
  var subprotocol2 = require_subprotocol();
@@ -33786,7 +34260,7 @@ var require_websocket_server = __commonJS({
33786
34260
  );
33787
34261
  }
33788
34262
  if (this._state > RUNNING) return abortHandshake(socket, 503);
33789
- const digest = createHash8("sha1").update(key + GUID).digest("base64");
34263
+ const digest = createHash10("sha1").update(key + GUID).digest("base64");
33790
34264
  const headers = [
33791
34265
  "HTTP/1.1 101 Switching Protocols",
33792
34266
  "Upgrade: websocket",
@@ -34080,7 +34554,7 @@ var init_provider = __esm({
34080
34554
  scheduleReconnect() {
34081
34555
  if (this.closed || this.reconnectTimer || this.targets.size === 0)
34082
34556
  return;
34083
- const delay2 = this.reconnectMs;
34557
+ const delay4 = this.reconnectMs;
34084
34558
  this.reconnectMs = Math.min(this.reconnectMs * 2, RECONNECT_MAX_MS);
34085
34559
  this.reconnectTimer = setTimeout(() => {
34086
34560
  this.reconnectTimer = null;
@@ -34088,7 +34562,7 @@ var init_provider = __esm({
34088
34562
  return;
34089
34563
  this.connectControl().then(() => this.logger?.info?.("proxy: control reconnected")).catch(() => {
34090
34564
  });
34091
- }, delay2);
34565
+ }, delay4);
34092
34566
  this.reconnectTimer.unref?.();
34093
34567
  }
34094
34568
  /** Pipe one inbound peer (raw bytes over a `/data` WS) to its target's port. */
@@ -38944,8 +39418,8 @@ function warnWindowsPipeAclOnce(logger, pipePath) {
38944
39418
  async function reclaimStaleSocket(socketPath) {
38945
39419
  if (!fs35__default.existsSync(socketPath))
38946
39420
  return;
38947
- const alive = await isRunnerUp(socketPath);
38948
- if (alive)
39421
+ const alive2 = await isRunnerUp(socketPath);
39422
+ if (alive2)
38949
39423
  return;
38950
39424
  if (await isRunnerUp(socketPath))
38951
39425
  return;
@@ -39069,6 +39543,37 @@ var init_unix_socket = __esm({
39069
39543
  warnedWindowsPipeAcl = false;
39070
39544
  }
39071
39545
  });
39546
+ async function handleComputerApprovalFocus({ session }, raw) {
39547
+ const command = computerApprovalFocusSchema.parse(raw);
39548
+ if (command.sessionId !== session.id)
39549
+ throw new Error("Computer Use session mismatch");
39550
+ const service = session.computerControl;
39551
+ if (service?.approvalFocus)
39552
+ await service.approvalFocus(command);
39553
+ }
39554
+ async function handleComputerSnapshot({ session }, raw) {
39555
+ z$1.object({}).strict().parse(raw);
39556
+ const service = session.computerControl;
39557
+ if (!service)
39558
+ return [];
39559
+ const snapshots = z$1.array(computerControlSnapshotSchema).max(256).parse(await service.snapshot());
39560
+ if (snapshots.some((snapshot) => snapshot.sessionId !== session.id))
39561
+ throw new Error("Computer Use session mismatch");
39562
+ return snapshots;
39563
+ }
39564
+ async function handleComputerControl({ session }, raw) {
39565
+ const command = computerControlCommandSchema.parse(raw);
39566
+ if (command.sessionId !== session.id)
39567
+ throw new Error("Computer Use session mismatch");
39568
+ const service = session.computerControl;
39569
+ if (!service)
39570
+ throw new Error("Computer Use control is not supported by this session");
39571
+ await service.control(command);
39572
+ }
39573
+ var init_computer_handlers = __esm({
39574
+ "../runner/dist/handlers/computer-handlers.js"() {
39575
+ }
39576
+ });
39072
39577
  function surfaceInputWithinCap(m) {
39073
39578
  let upper = 2;
39074
39579
  let primitiveOnly = true;
@@ -39100,13 +39605,15 @@ function surfaceInputWithinCap(m) {
39100
39605
  var RUNNER_PROTOCOL_VERSION, MIN_COMPATIBLE_PROTOCOL_VERSION, RunnerMethod, RunnerNotification, attachmentSchema, principalSchema, attachParamsSchema, runTurnParamsSchema, abortParamsSchema, setResolverParamsSchema, modeSetActiveParamsSchema, sessionSetReasoningParamsSchema, MAX_HISTORY_PAGE_LIMIT, sessionLoadHistoryParamsSchema, providerSetActiveParamsSchema, providerSetEnabledParamsSchema, providerConfigureParamsSchema, permissionAddAllowParamsSchema, commandRunParamsSchema, MAX_TRANSCRIBE_AUDIO_B64_BYTES, MAX_SYNTHESIZE_TEXT_BYTES, MEDIA_DESCRIPTOR_MAX, transcribeParamsSchema, synthesizeParamsSchema, mcpEnableAndAttachParamsSchema, mcpDetachParamsSchema, workflowSetEnabledParamsSchema, workflowRunParamsSchema, workflowValidateDraftParamsSchema, workflowSaveParamsSchema, workflowGetRunParamsSchema, workflowResumeParamsSchema, surfaceOpenParamsSchema, MAX_SURFACE_INPUT_BYTES, surfaceInputParamsSchema, surfaceResizeParamsSchema, surfaceCloseParamsSchema;
39101
39606
  var init_protocol2 = __esm({
39102
39607
  "../runner/dist/protocol.js"() {
39103
- RUNNER_PROTOCOL_VERSION = 11;
39608
+ RUNNER_PROTOCOL_VERSION = 15;
39104
39609
  MIN_COMPATIBLE_PROTOCOL_VERSION = 1;
39105
39610
  RunnerMethod = {
39106
39611
  /** client->server: handshake; returns the initial info snapshot. */
39107
39612
  Attach: "attach",
39108
39613
  /** client->server: re-fetch the registry snapshot. */
39109
39614
  GetInfo: "getInfo",
39615
+ ComputerSnapshot: "computer.snapshot",
39616
+ ComputerControl: "computer.control",
39110
39617
  /** client->server: start a turn; returns its turnId. Events stream separately. */
39111
39618
  RunTurn: "runTurn",
39112
39619
  /** client->server: abort an in-flight turn. */
@@ -39158,6 +39665,7 @@ var init_protocol2 = __esm({
39158
39665
  WorkflowList: "workflow.list",
39159
39666
  /** client->server: enable/disable a workflow. */
39160
39667
  WorkflowSetEnabled: "workflow.setEnabled",
39668
+ WorkflowDelete: "workflow.delete",
39161
39669
  /** client->server: run a workflow now. */
39162
39670
  WorkflowRun: "workflow.run",
39163
39671
  /** client->server: validate a draft workflow YAML (builder). */
@@ -39172,6 +39680,8 @@ var init_protocol2 = __esm({
39172
39680
  * reported version so an older runner returns an actionable error.
39173
39681
  */
39174
39682
  WorkflowResume: "workflow.resume",
39683
+ WorkflowApprovals: "workflow.approvals",
39684
+ ComputerApprovalFocus: "computer.approvalFocus",
39175
39685
  /** client->server: list available surface kinds + availability (v8). */
39176
39686
  SurfaceList: "surface.list",
39177
39687
  /** client->server: open (or attach to the shared) surface instance (v8). */
@@ -39351,6 +39861,86 @@ var init_protocol2 = __esm({
39351
39861
  });
39352
39862
  }
39353
39863
  });
39864
+ async function handleWorkflowDelete(ctx, raw) {
39865
+ const { name } = z.object({ name: z.string().min(1).max(120) }).strict().parse(raw);
39866
+ const view = ctx.session.workflows;
39867
+ if (!view?.delete)
39868
+ throw new Error("Workflow deletion unavailable; update the runner");
39869
+ await view.delete(name);
39870
+ }
39871
+ async function handleWorkflowApprovals(ctx, raw) {
39872
+ const command = approvalCommandSchema.parse(raw);
39873
+ const view = ctx.session.workflows?.approvals;
39874
+ if (!view)
39875
+ throw new Error("Workflow approvals unavailable; update the runner");
39876
+ if (command.action === "list")
39877
+ return view.list();
39878
+ if (command.action === "decide")
39879
+ return view.decide(command.id, command.choice);
39880
+ if (command.action === "cancel")
39881
+ return view.cancel(command.id);
39882
+ return view.revoke(command.id);
39883
+ }
39884
+ async function handleWorkflowList(ctx) {
39885
+ const view = ctx.session.workflows;
39886
+ if (!view)
39887
+ return [];
39888
+ return [...await view.list()];
39889
+ }
39890
+ async function handleWorkflowSetEnabled(ctx, raw) {
39891
+ const params = workflowSetEnabledParamsSchema.parse(raw);
39892
+ const view = ctx.session.workflows;
39893
+ if (!view)
39894
+ throw new Error("workflows plugin not loaded");
39895
+ await view.setEnabled(params.name, params.enabled);
39896
+ }
39897
+ async function handleWorkflowRun(ctx, raw) {
39898
+ const params = workflowRunParamsSchema.parse(raw);
39899
+ const view = ctx.session.workflows;
39900
+ if (!view)
39901
+ throw new Error("workflows plugin not loaded");
39902
+ return view.run(params.name);
39903
+ }
39904
+ async function handleWorkflowValidateDraft(ctx, raw) {
39905
+ const params = workflowValidateDraftParamsSchema.parse(raw);
39906
+ const view = ctx.session.workflows;
39907
+ if (!view?.validateDraft)
39908
+ throw new Error("workflows builder not supported on this runner");
39909
+ return view.validateDraft(params.yaml);
39910
+ }
39911
+ async function handleWorkflowSave(ctx, raw) {
39912
+ const params = workflowSaveParamsSchema.parse(raw);
39913
+ const view = ctx.session.workflows;
39914
+ if (!view?.save)
39915
+ throw new Error("workflows builder not supported on this runner");
39916
+ return view.save(params.yaml, params.previousName);
39917
+ }
39918
+ async function handleWorkflowGetRun(ctx, raw) {
39919
+ const params = workflowGetRunParamsSchema.parse(raw);
39920
+ const view = ctx.session.workflows;
39921
+ if (!view?.getRun)
39922
+ throw new Error("workflows builder not supported on this runner");
39923
+ return await view.getRun(params.name) ?? null;
39924
+ }
39925
+ async function handleWorkflowResume(ctx, raw) {
39926
+ const params = workflowResumeParamsSchema.parse(raw);
39927
+ const view = ctx.session.workflows;
39928
+ if (!view?.resume)
39929
+ throw new Error("workflow resume not supported on this runner");
39930
+ return view.resume(params.runId, params.reply);
39931
+ }
39932
+ var approvalCommandSchema;
39933
+ var init_workflow_handlers = __esm({
39934
+ "../runner/dist/handlers/workflow-handlers.js"() {
39935
+ init_protocol2();
39936
+ approvalCommandSchema = z.discriminatedUnion("action", [
39937
+ z.object({ action: z.literal("list") }).strict(),
39938
+ z.object({ action: z.literal("decide"), id: z.string().uuid(), choice: z.enum(["allow_once", "allow_always", "deny"]) }).strict(),
39939
+ z.object({ action: z.literal("revoke"), id: z.string().uuid() }).strict(),
39940
+ z.object({ action: z.literal("cancel"), id: z.string().uuid() }).strict()
39941
+ ]);
39942
+ }
39943
+ });
39354
39944
 
39355
39945
  // ../runner/dist/handlers/provider-handlers.js
39356
39946
  async function handleProviderSetActive(ctx, raw) {
@@ -39502,61 +40092,6 @@ var init_mcp_handlers = __esm({
39502
40092
  }
39503
40093
  });
39504
40094
 
39505
- // ../runner/dist/handlers/workflow-handlers.js
39506
- async function handleWorkflowList(ctx) {
39507
- const view = ctx.session.workflows;
39508
- if (!view)
39509
- return [];
39510
- return [...await view.list()];
39511
- }
39512
- async function handleWorkflowSetEnabled(ctx, raw) {
39513
- const params = workflowSetEnabledParamsSchema.parse(raw);
39514
- const view = ctx.session.workflows;
39515
- if (!view)
39516
- throw new Error("workflows plugin not loaded");
39517
- await view.setEnabled(params.name, params.enabled);
39518
- }
39519
- async function handleWorkflowRun(ctx, raw) {
39520
- const params = workflowRunParamsSchema.parse(raw);
39521
- const view = ctx.session.workflows;
39522
- if (!view)
39523
- throw new Error("workflows plugin not loaded");
39524
- return view.run(params.name);
39525
- }
39526
- async function handleWorkflowValidateDraft(ctx, raw) {
39527
- const params = workflowValidateDraftParamsSchema.parse(raw);
39528
- const view = ctx.session.workflows;
39529
- if (!view?.validateDraft)
39530
- throw new Error("workflows builder not supported on this runner");
39531
- return view.validateDraft(params.yaml);
39532
- }
39533
- async function handleWorkflowSave(ctx, raw) {
39534
- const params = workflowSaveParamsSchema.parse(raw);
39535
- const view = ctx.session.workflows;
39536
- if (!view?.save)
39537
- throw new Error("workflows builder not supported on this runner");
39538
- return view.save(params.yaml, params.previousName);
39539
- }
39540
- async function handleWorkflowGetRun(ctx, raw) {
39541
- const params = workflowGetRunParamsSchema.parse(raw);
39542
- const view = ctx.session.workflows;
39543
- if (!view?.getRun)
39544
- throw new Error("workflows builder not supported on this runner");
39545
- return await view.getRun(params.name) ?? null;
39546
- }
39547
- async function handleWorkflowResume(ctx, raw) {
39548
- const params = workflowResumeParamsSchema.parse(raw);
39549
- const view = ctx.session.workflows;
39550
- if (!view?.resume)
39551
- throw new Error("workflow resume not supported on this runner");
39552
- return view.resume(params.runId, params.reply);
39553
- }
39554
- var init_workflow_handlers = __esm({
39555
- "../runner/dist/handlers/workflow-handlers.js"() {
39556
- init_protocol2();
39557
- }
39558
- });
39559
-
39560
40095
  // ../runner/dist/handlers/surface-handlers.js
39561
40096
  async function handleSurfaceList(ctx) {
39562
40097
  return [...await ctx.session.surfaces.list()];
@@ -39658,6 +40193,8 @@ var init_server2 = __esm({
39658
40193
  init_jsonrpc();
39659
40194
  init_unix_socket();
39660
40195
  init_socket_path();
40196
+ init_computer_handlers();
40197
+ init_workflow_handlers();
39661
40198
  init_protocol2();
39662
40199
  init_handlers();
39663
40200
  CLIENT_REQUEST_TIMEOUT_MS = 10 * 60 * 1e3;
@@ -39748,6 +40285,8 @@ var init_server2 = __esm({
39748
40285
  const ctx = this.handlerCtx;
39749
40286
  peer.handle(RunnerMethod.Attach, (raw) => this.handleAttach(client2, raw));
39750
40287
  peer.handle(RunnerMethod.GetInfo, () => this.session.getInfo());
40288
+ peer.handle(RunnerMethod.ComputerSnapshot, (raw) => handleComputerSnapshot(ctx, raw));
40289
+ peer.handle(RunnerMethod.ComputerControl, (raw) => handleComputerControl(ctx, raw));
39751
40290
  peer.handle(RunnerMethod.RunTurn, (raw) => this.handleRunTurn(client2, raw));
39752
40291
  peer.handle(RunnerMethod.Abort, (raw) => this.handleAbort(client2, raw));
39753
40292
  peer.handle(RunnerMethod.SessionReset, () => this.handleSessionReset());
@@ -39768,11 +40307,14 @@ var init_server2 = __esm({
39768
40307
  peer.handle(RunnerMethod.McpDetach, (raw) => handleMcpDetach(ctx, raw));
39769
40308
  peer.handle(RunnerMethod.WorkflowList, () => handleWorkflowList(ctx));
39770
40309
  peer.handle(RunnerMethod.WorkflowSetEnabled, (raw) => handleWorkflowSetEnabled(ctx, raw));
40310
+ peer.handle(RunnerMethod.WorkflowDelete, (raw) => handleWorkflowDelete(ctx, raw));
39771
40311
  peer.handle(RunnerMethod.WorkflowRun, (raw) => handleWorkflowRun(ctx, raw));
39772
40312
  peer.handle(RunnerMethod.WorkflowValidateDraft, (raw) => handleWorkflowValidateDraft(ctx, raw));
39773
40313
  peer.handle(RunnerMethod.WorkflowSave, (raw) => handleWorkflowSave(ctx, raw));
39774
40314
  peer.handle(RunnerMethod.WorkflowGetRun, (raw) => handleWorkflowGetRun(ctx, raw));
39775
40315
  peer.handle(RunnerMethod.WorkflowResume, (raw) => handleWorkflowResume(ctx, raw));
40316
+ peer.handle(RunnerMethod.WorkflowApprovals, (raw) => handleWorkflowApprovals(ctx, raw));
40317
+ peer.handle(RunnerMethod.ComputerApprovalFocus, (raw) => handleComputerApprovalFocus(ctx, raw));
39776
40318
  peer.handle(RunnerMethod.SurfaceList, () => handleSurfaceList(ctx));
39777
40319
  peer.handle(RunnerMethod.SurfaceOpen, (raw) => handleSurfaceOpen(ctx, raw));
39778
40320
  peer.handle(RunnerMethod.SurfaceInput, (raw) => handleSurfaceInput(ctx, raw));
@@ -39976,16 +40518,16 @@ var init_server2 = __esm({
39976
40518
  };
39977
40519
  }
39978
40520
  async resolvePermission(call, ctx) {
39979
- const scope = this.scope.getStore();
39980
- if (scope && scope.client.handlesPermission && !scope.client.peer.isClosed) {
40521
+ const scope2 = this.scope.getStore();
40522
+ if (scope2 && scope2.client.handlesPermission && !scope2.client.peer.isClosed) {
39981
40523
  try {
39982
- return await scope.client.peer.request(
40524
+ return await scope2.client.peer.request(
39983
40525
  RunnerMethod.PermissionCheck,
39984
- { turnId: scope.turnId, call, ctx },
40526
+ { turnId: scope2.turnId, call, ctx },
39985
40527
  // A client can stay socket-connected yet never answer (hung renderer
39986
40528
  // that doesn't drop the link); the turn's signal + a bounded timeout
39987
40529
  // make this fall through to deny instead of stalling the turn forever.
39988
- { signal: this.turnControllers.get(scope.turnId)?.controller.signal, timeoutMs: CLIENT_REQUEST_TIMEOUT_MS }
40530
+ { signal: this.turnControllers.get(scope2.turnId)?.controller.signal, timeoutMs: CLIENT_REQUEST_TIMEOUT_MS }
39989
40531
  );
39990
40532
  } catch {
39991
40533
  return { mode: "deny", reason: "permission client unavailable" };
@@ -39994,11 +40536,11 @@ var init_server2 = __esm({
39994
40536
  return this.fallbackPermission.check(call, ctx);
39995
40537
  }
39996
40538
  async resolveApproval(request) {
39997
- const scope = this.scope.getStore();
39998
- if (scope) {
39999
- if (scope.client.handlesApproval && !scope.client.peer.isClosed) {
40539
+ const scope2 = this.scope.getStore();
40540
+ if (scope2) {
40541
+ if (scope2.client.handlesApproval && !scope2.client.peer.isClosed) {
40000
40542
  try {
40001
- return await scope.client.peer.request(RunnerMethod.ApprovalConfirm, { turnId: scope.turnId, request }, { signal: this.turnControllers.get(scope.turnId)?.controller.signal, timeoutMs: CLIENT_REQUEST_TIMEOUT_MS });
40543
+ return await scope2.client.peer.request(RunnerMethod.ApprovalConfirm, { turnId: scope2.turnId, request }, { signal: this.turnControllers.get(scope2.turnId)?.controller.signal, timeoutMs: CLIENT_REQUEST_TIMEOUT_MS });
40002
40544
  } catch {
40003
40545
  return defaultApproval(request);
40004
40546
  }
@@ -40022,6 +40564,33 @@ var init_server2 = __esm({
40022
40564
  };
40023
40565
  }
40024
40566
  });
40567
+ function makeComputerControlView(ctx) {
40568
+ return {
40569
+ approvalFocus: async (input) => {
40570
+ ctx.requireServerProtocol(13, "Computer Use approval focus");
40571
+ const command = computerApprovalFocusSchema.parse(input);
40572
+ if (command.sessionId !== ctx.requireInfo().sessionId)
40573
+ throw new Error("Computer Use session mismatch");
40574
+ await ctx.peer.request(RunnerMethod.ComputerApprovalFocus, command);
40575
+ },
40576
+ snapshot: async () => {
40577
+ ctx.requireServerProtocol(12, "Reading Computer Use control");
40578
+ return z$1.array(computerControlSnapshotSchema).max(256).parse(await ctx.peer.request(RunnerMethod.ComputerSnapshot, {}));
40579
+ },
40580
+ control: async (input) => {
40581
+ ctx.requireServerProtocol(12, "Controlling Computer Use");
40582
+ const command = computerControlCommandSchema.parse(input);
40583
+ if (command.sessionId !== ctx.requireInfo().sessionId)
40584
+ throw new Error("Computer Use session mismatch");
40585
+ await ctx.peer.request(RunnerMethod.ComputerControl, command);
40586
+ }
40587
+ };
40588
+ }
40589
+ var init_computer_control = __esm({
40590
+ "../runner/dist/client-views/computer-control.js"() {
40591
+ init_protocol2();
40592
+ }
40593
+ });
40025
40594
  function fakeProvider(name, models) {
40026
40595
  return {
40027
40596
  name,
@@ -40312,11 +40881,31 @@ var init_provider_admin = __esm({
40312
40881
  init_protocol2();
40313
40882
  }
40314
40883
  });
40315
-
40316
- // ../runner/dist/client-views/workflows.js
40317
40884
  function makeWorkflowsView(ctx) {
40318
40885
  const { peer, requireServerProtocol } = ctx;
40319
40886
  return {
40887
+ delete: async (name) => {
40888
+ requireServerProtocol(15, "Workflow deletion");
40889
+ await peer.request(RunnerMethod.WorkflowDelete, { name });
40890
+ },
40891
+ approvals: {
40892
+ cancel: async (id) => {
40893
+ requireServerProtocol(13, "Workflow approvals");
40894
+ await peer.request(RunnerMethod.WorkflowApprovals, { action: "cancel", id });
40895
+ },
40896
+ list: async () => {
40897
+ requireServerProtocol(13, "Workflow approvals");
40898
+ return workflowApprovalItemsSchema.parse(await peer.request(RunnerMethod.WorkflowApprovals, { action: "list" }));
40899
+ },
40900
+ decide: async (id, choice) => {
40901
+ requireServerProtocol(13, "Workflow approvals");
40902
+ await peer.request(RunnerMethod.WorkflowApprovals, { action: "decide", id, choice });
40903
+ },
40904
+ revoke: async (id) => {
40905
+ requireServerProtocol(13, "Workflow approvals");
40906
+ await peer.request(RunnerMethod.WorkflowApprovals, { action: "revoke", id });
40907
+ }
40908
+ },
40320
40909
  list: () => peer.request(RunnerMethod.WorkflowList),
40321
40910
  setEnabled: async (name, enabled) => {
40322
40911
  await peer.request(RunnerMethod.WorkflowSetEnabled, {
@@ -40545,6 +41134,7 @@ var TurnStream, MAX_COMPLETED_TURNS, RemoteSession, DEFAULT_RUNNER_PORTS, RECOVE
40545
41134
  var init_remote_session = __esm({
40546
41135
  "../runner/dist/remote-session.js"() {
40547
41136
  init_dist2();
41137
+ init_computer_control();
40548
41138
  init_jsonrpc();
40549
41139
  init_client_views();
40550
41140
  init_unix_socket();
@@ -40604,6 +41194,7 @@ var init_remote_session = __esm({
40604
41194
  permissions;
40605
41195
  mcpAdmin;
40606
41196
  providerAdmin;
41197
+ computerControl;
40607
41198
  workflows;
40608
41199
  /**
40609
41200
  * Turns that completed before their `runTurn` stream was registered. A fast
@@ -40678,17 +41269,17 @@ var init_remote_session = __esm({
40678
41269
  this.mirror.clear();
40679
41270
  });
40680
41271
  this.peer.handle(RunnerMethod.PermissionCheck, (params) => {
40681
- const { call, ctx } = params;
41272
+ const { call, ctx, turnId } = params;
40682
41273
  if (!this.permissionResolver) {
40683
41274
  return { mode: "deny", reason: "no permission resolver on client" };
40684
41275
  }
40685
- return this.permissionResolver.check(call, ctx);
41276
+ return this.permissionResolver.check(call, { ...ctx, turnId: String(turnId) });
40686
41277
  });
40687
41278
  this.peer.handle(RunnerMethod.ApprovalConfirm, (params) => {
40688
- const { request } = params;
41279
+ const { request, turnId } = params;
40689
41280
  if (!this.approvalResolver)
40690
41281
  return defaultApproval2(request);
40691
- return this.approvalResolver.confirm(request);
41282
+ return this.approvalResolver.confirm(request, { turnId: String(turnId) });
40692
41283
  });
40693
41284
  this.peer.onClose(() => {
40694
41285
  for (const stream of this.turnStreams.values())
@@ -40714,6 +41305,7 @@ var init_remote_session = __esm({
40714
41305
  this.permissions = makePermissionsView(view);
40715
41306
  this.mcpAdmin = makeMcpAdminView(view);
40716
41307
  this.providerAdmin = makeProviderAdminView(view);
41308
+ this.computerControl = makeComputerControlView(view);
40717
41309
  this.workflows = makeWorkflowsView(view);
40718
41310
  }
40719
41311
  /**
@@ -44572,10 +45164,10 @@ var require_react_production_min = __commonJS({
44572
45164
  var w = /* @__PURE__ */ Symbol.for("react.suspense");
44573
45165
  var x3 = /* @__PURE__ */ Symbol.for("react.memo");
44574
45166
  var y2 = /* @__PURE__ */ Symbol.for("react.lazy");
44575
- var z63 = Symbol.iterator;
45167
+ var z68 = Symbol.iterator;
44576
45168
  function A(a) {
44577
45169
  if (null === a || "object" !== typeof a) return null;
44578
- a = z63 && a[z63] || a["@@iterator"];
45170
+ a = z68 && a[z68] || a["@@iterator"];
44579
45171
  return "function" === typeof a ? a : null;
44580
45172
  }
44581
45173
  var B2 = { isMounted: function() {
@@ -46458,7 +47050,7 @@ var require_react_development = __commonJS({
46458
47050
  validatePropTypes(newElement);
46459
47051
  return newElement;
46460
47052
  }
46461
- function startTransition(scope, options) {
47053
+ function startTransition(scope2, options) {
46462
47054
  var prevTransition = ReactCurrentBatchConfig.transition;
46463
47055
  ReactCurrentBatchConfig.transition = {};
46464
47056
  var currentTransition = ReactCurrentBatchConfig.transition;
@@ -46466,7 +47058,7 @@ var require_react_development = __commonJS({
46466
47058
  ReactCurrentBatchConfig.transition._updatedFibers = /* @__PURE__ */ new Set();
46467
47059
  }
46468
47060
  try {
46469
- scope();
47061
+ scope2();
46470
47062
  } finally {
46471
47063
  ReactCurrentBatchConfig.transition = prevTransition;
46472
47064
  {
@@ -46907,13 +47499,13 @@ __export(base_exports, {
46907
47499
  exitAlternativeScreen: () => exitAlternativeScreen,
46908
47500
  iTerm: () => iTerm,
46909
47501
  image: () => image,
46910
- link: () => link,
47502
+ link: () => link2,
46911
47503
  scrollDown: () => scrollDown,
46912
47504
  scrollUp: () => scrollUp,
46913
47505
  setCwd: () => setCwd,
46914
47506
  synchronizedOutput: () => synchronizedOutput
46915
47507
  });
46916
- var ESC, OSC, BEL, SEP, isTerminalApp, isWindows2, isTmux, cwdFunction, wrapOsc, cursorTo, cursorMove, cursorUp, cursorDown, cursorForward, cursorBackward, cursorLeft, cursorSavePosition, cursorRestorePosition, cursorGetPosition, cursorNextLine, cursorPrevLine, cursorHide, cursorShow, eraseLines, eraseEndLine, eraseStartLine, eraseLine, eraseDown, eraseUp, eraseScreen, scrollUp, scrollDown, clearScreen, clearViewport, isOldWindows, clearTerminal, enterAlternativeScreen, exitAlternativeScreen, beginSynchronizedOutput, endSynchronizedOutput, synchronizedOutput, beep, link, image, iTerm, ConEmu, setCwd;
47508
+ var ESC, OSC, BEL, SEP, isTerminalApp, isWindows2, isTmux, cwdFunction, wrapOsc, cursorTo, cursorMove, cursorUp, cursorDown, cursorForward, cursorBackward, cursorLeft, cursorSavePosition, cursorRestorePosition, cursorGetPosition, cursorNextLine, cursorPrevLine, cursorHide, cursorShow, eraseLines, eraseEndLine, eraseStartLine, eraseLine, eraseDown, eraseUp, eraseScreen, scrollUp, scrollDown, clearScreen, clearViewport, isOldWindows, clearTerminal, enterAlternativeScreen, exitAlternativeScreen, beginSynchronizedOutput, endSynchronizedOutput, synchronizedOutput, beep, link2, image, iTerm, ConEmu, setCwd;
46917
47509
  var init_base = __esm({
46918
47510
  "../../node_modules/.pnpm/ansi-escapes@7.3.0/node_modules/ansi-escapes/base.js"() {
46919
47511
  init_environment();
@@ -47013,7 +47605,7 @@ var init_base = __esm({
47013
47605
  endSynchronizedOutput = ESC + "?2026l";
47014
47606
  synchronizedOutput = (text2) => beginSynchronizedOutput + text2 + endSynchronizedOutput;
47015
47607
  beep = BEL;
47016
- link = (text2, url) => {
47608
+ link2 = (text2, url) => {
47017
47609
  const openLink = wrapOsc(`${OSC}8${SEP}${SEP}${url}${BEL}`);
47018
47610
  const closeLink = wrapOsc(`${OSC}8${SEP}${SEP}${BEL}`);
47019
47611
  return openLink + text2 + closeLink;
@@ -47382,7 +47974,7 @@ var init_yoga_wasm_base64_esm = __esm({
47382
47974
  h.noExitRuntime || true;
47383
47975
  "object" != typeof WebAssembly && x3("no native wasm support detected");
47384
47976
  var fa, ha = false;
47385
- function z63(a, b, c) {
47977
+ function z68(a, b, c) {
47386
47978
  c = b + c;
47387
47979
  for (var d2 = ""; !(b >= c); ) {
47388
47980
  var e2 = a[b++];
@@ -48032,7 +48624,7 @@ var init_yoga_wasm_base64_esm = __esm({
48032
48624
  return b;
48033
48625
  }, Jb = {
48034
48626
  l: function(a, b, c, d2) {
48035
- x3("Assertion failed: " + (a ? z63(A, a) : "") + ", at: " + [b ? b ? z63(A, b) : "" : "unknown filename", c, d2 ? d2 ? z63(A, d2) : "" : "unknown function"]);
48627
+ x3("Assertion failed: " + (a ? z68(A, a) : "") + ", at: " + [b ? b ? z68(A, b) : "" : "unknown filename", c, d2 ? d2 ? z68(A, d2) : "" : "unknown function"]);
48036
48628
  },
48037
48629
  q: function(a, b, c) {
48038
48630
  a = N3(a);
@@ -48285,7 +48877,7 @@ var init_yoga_wasm_base64_esm = __esm({
48285
48877
  if (c) for (var g = f, k2 = 0; k2 <= e2; ++k2) {
48286
48878
  var m = f + k2;
48287
48879
  if (k2 == e2 || 0 == A[m]) {
48288
- g = g ? z63(A, g, m - g) : "";
48880
+ g = g ? z68(A, g, m - g) : "";
48289
48881
  if (void 0 === l) var l = g;
48290
48882
  else l += String.fromCharCode(0), l += g;
48291
48883
  g = m + 1;
@@ -48482,7 +49074,7 @@ var init_yoga_wasm_base64_esm = __esm({
48482
49074
  b += 8;
48483
49075
  for (var m = 0; m < k2; m++) {
48484
49076
  var l = A[g + m], n = Fb[a];
48485
- 0 === l || 10 === l ? ((1 === a ? ea : v)(z63(n, 0)), n.length = 0) : n.push(l);
49077
+ 0 === l || 10 === l ? ((1 === a ? ea : v)(z68(n, 0)), n.length = 0) : n.push(l);
48486
49078
  }
48487
49079
  e2 += k2;
48488
49080
  }
@@ -48970,7 +49562,7 @@ var require_scheduler_production_min = __commonJS({
48970
49562
  var u = 1;
48971
49563
  var v = null;
48972
49564
  var y2 = 3;
48973
- var z63 = false;
49565
+ var z68 = false;
48974
49566
  var A = false;
48975
49567
  var B2 = false;
48976
49568
  var D2 = "function" === typeof setTimeout ? setTimeout : null;
@@ -48997,7 +49589,7 @@ var require_scheduler_production_min = __commonJS({
48997
49589
  function J3(a, b) {
48998
49590
  A = false;
48999
49591
  B2 && (B2 = false, E(L2), L2 = -1);
49000
- z63 = true;
49592
+ z68 = true;
49001
49593
  var c = y2;
49002
49594
  try {
49003
49595
  G2(b);
@@ -49021,7 +49613,7 @@ var require_scheduler_production_min = __commonJS({
49021
49613
  }
49022
49614
  return w;
49023
49615
  } finally {
49024
- v = null, y2 = c, z63 = false;
49616
+ v = null, y2 = c, z68 = false;
49025
49617
  }
49026
49618
  }
49027
49619
  var N3 = false;
@@ -49078,7 +49670,7 @@ var require_scheduler_production_min = __commonJS({
49078
49670
  a.callback = null;
49079
49671
  };
49080
49672
  exports.unstable_continueExecution = function() {
49081
- A || z63 || (A = true, I2(J3));
49673
+ A || z68 || (A = true, I2(J3));
49082
49674
  };
49083
49675
  exports.unstable_forceFrameRate = function(a) {
49084
49676
  0 > a || 125 < a ? console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported") : P2 = 0 < a ? Math.floor(1e3 / a) : 5;
@@ -49151,7 +49743,7 @@ var require_scheduler_production_min = __commonJS({
49151
49743
  }
49152
49744
  e2 = c + e2;
49153
49745
  a = { id: u++, callback: b, priorityLevel: a, startTime: c, expirationTime: e2, sortIndex: -1 };
49154
- c > d2 ? (a.sortIndex = c, f(t, a), null === h(r) && a === h(t) && (B2 ? (E(L2), L2 = -1) : B2 = true, K3(H3, c - d2))) : (a.sortIndex = e2, f(r, a), A || z63 || (A = true, I2(J3)));
49746
+ c > d2 ? (a.sortIndex = c, f(t, a), null === h(r) && a === h(t) && (B2 ? (E(L2), L2 = -1) : B2 = true, K3(H3, c - d2))) : (a.sortIndex = e2, f(r, a), A || z68 || (A = true, I2(J3)));
49155
49747
  return a;
49156
49748
  };
49157
49749
  exports.unstable_shouldYield = M3;
@@ -49425,9 +50017,9 @@ var require_scheduler_development = __commonJS({
49425
50017
  var currentTime = exports.unstable_now();
49426
50018
  var startTime2;
49427
50019
  if (typeof options === "object" && options !== null) {
49428
- var delay2 = options.delay;
49429
- if (typeof delay2 === "number" && delay2 > 0) {
49430
- startTime2 = currentTime + delay2;
50020
+ var delay4 = options.delay;
50021
+ if (typeof delay4 === "number" && delay4 > 0) {
50022
+ startTime2 = currentTime + delay4;
49431
50023
  } else {
49432
50024
  startTime2 = currentTime;
49433
50025
  }
@@ -49908,7 +50500,7 @@ var require_react_reconciler_production_min = __commonJS({
49908
50500
  gc[hc] = a.current;
49909
50501
  a.current = b;
49910
50502
  }
49911
- var jc = {}, x3 = ic(jc), z63 = ic(false), kc = jc;
50503
+ var jc = {}, x3 = ic(jc), z68 = ic(false), kc = jc;
49912
50504
  function mc(a, b) {
49913
50505
  var c = a.type.contextTypes;
49914
50506
  if (!c) return jc;
@@ -49924,13 +50516,13 @@ var require_react_reconciler_production_min = __commonJS({
49924
50516
  return null !== a && void 0 !== a;
49925
50517
  }
49926
50518
  function nc() {
49927
- q3(z63);
50519
+ q3(z68);
49928
50520
  q3(x3);
49929
50521
  }
49930
50522
  function oc(a, b, c) {
49931
50523
  if (x3.current !== jc) throw Error(n(168));
49932
50524
  v(x3, b);
49933
- v(z63, c);
50525
+ v(z68, c);
49934
50526
  }
49935
50527
  function pc(a, b, c) {
49936
50528
  var d2 = a.stateNode;
@@ -49944,14 +50536,14 @@ var require_react_reconciler_production_min = __commonJS({
49944
50536
  a = (a = a.stateNode) && a.__reactInternalMemoizedMergedChildContext || jc;
49945
50537
  kc = x3.current;
49946
50538
  v(x3, a);
49947
- v(z63, z63.current);
50539
+ v(z68, z68.current);
49948
50540
  return true;
49949
50541
  }
49950
50542
  function rc(a, b, c) {
49951
50543
  var d2 = a.stateNode;
49952
50544
  if (!d2) throw Error(n(169));
49953
- c ? (a = pc(a, b, kc), d2.__reactInternalMemoizedMergedChildContext = a, q3(z63), q3(x3), v(x3, a)) : q3(z63);
49954
- v(z63, c);
50545
+ c ? (a = pc(a, b, kc), d2.__reactInternalMemoizedMergedChildContext = a, q3(z68), q3(x3), v(x3, a)) : q3(z68);
50546
+ v(z68, c);
49955
50547
  }
49956
50548
  var tc = Math.clz32 ? Math.clz32 : sc, uc = Math.log, vc = Math.LN2;
49957
50549
  function sc(a) {
@@ -51549,7 +52141,7 @@ var require_react_reconciler_production_min = __commonJS({
51549
52141
  g.state = p;
51550
52142
  ke2(b, d2, g, e2);
51551
52143
  k2 = b.memoizedState;
51552
- h !== d2 || p !== k2 || z63.current || de2 ? ("function" === typeof m && (yf(b, c, m, d2), k2 = b.memoizedState), (h = de2 || Af(b, c, h, d2, p, k2, l)) ? (r || "function" !== typeof g.UNSAFE_componentWillMount && "function" !== typeof g.componentWillMount || ("function" === typeof g.componentWillMount && g.componentWillMount(), "function" === typeof g.UNSAFE_componentWillMount && g.UNSAFE_componentWillMount()), "function" === typeof g.componentDidMount && (b.flags |= 4194308)) : ("function" === typeof g.componentDidMount && (b.flags |= 4194308), b.memoizedProps = d2, b.memoizedState = k2), g.props = d2, g.state = k2, g.context = l, d2 = h) : ("function" === typeof g.componentDidMount && (b.flags |= 4194308), d2 = false);
52144
+ h !== d2 || p !== k2 || z68.current || de2 ? ("function" === typeof m && (yf(b, c, m, d2), k2 = b.memoizedState), (h = de2 || Af(b, c, h, d2, p, k2, l)) ? (r || "function" !== typeof g.UNSAFE_componentWillMount && "function" !== typeof g.componentWillMount || ("function" === typeof g.componentWillMount && g.componentWillMount(), "function" === typeof g.UNSAFE_componentWillMount && g.UNSAFE_componentWillMount()), "function" === typeof g.componentDidMount && (b.flags |= 4194308)) : ("function" === typeof g.componentDidMount && (b.flags |= 4194308), b.memoizedProps = d2, b.memoizedState = k2), g.props = d2, g.state = k2, g.context = l, d2 = h) : ("function" === typeof g.componentDidMount && (b.flags |= 4194308), d2 = false);
51553
52145
  } else {
51554
52146
  g = b.stateNode;
51555
52147
  fe2(a, b);
@@ -51567,7 +52159,7 @@ var require_react_reconciler_production_min = __commonJS({
51567
52159
  g.state = p;
51568
52160
  ke2(b, d2, g, e2);
51569
52161
  var w = b.memoizedState;
51570
- h !== r || p !== w || z63.current || de2 ? ("function" === typeof B2 && (yf(b, c, B2, d2), w = b.memoizedState), (l = de2 || Af(b, c, l, d2, p, w, k2) || false) ? (m || "function" !== typeof g.UNSAFE_componentWillUpdate && "function" !== typeof g.componentWillUpdate || ("function" === typeof g.componentWillUpdate && g.componentWillUpdate(d2, w, k2), "function" === typeof g.UNSAFE_componentWillUpdate && g.UNSAFE_componentWillUpdate(d2, w, k2)), "function" === typeof g.componentDidUpdate && (b.flags |= 4), "function" === typeof g.getSnapshotBeforeUpdate && (b.flags |= 1024)) : ("function" !== typeof g.componentDidUpdate || h === a.memoizedProps && p === a.memoizedState || (b.flags |= 4), "function" !== typeof g.getSnapshotBeforeUpdate || h === a.memoizedProps && p === a.memoizedState || (b.flags |= 1024), b.memoizedProps = d2, b.memoizedState = w), g.props = d2, g.state = w, g.context = k2, d2 = l) : ("function" !== typeof g.componentDidUpdate || h === a.memoizedProps && p === a.memoizedState || (b.flags |= 4), "function" !== typeof g.getSnapshotBeforeUpdate || h === a.memoizedProps && p === a.memoizedState || (b.flags |= 1024), d2 = false);
52162
+ h !== r || p !== w || z68.current || de2 ? ("function" === typeof B2 && (yf(b, c, B2, d2), w = b.memoizedState), (l = de2 || Af(b, c, l, d2, p, w, k2) || false) ? (m || "function" !== typeof g.UNSAFE_componentWillUpdate && "function" !== typeof g.componentWillUpdate || ("function" === typeof g.componentWillUpdate && g.componentWillUpdate(d2, w, k2), "function" === typeof g.UNSAFE_componentWillUpdate && g.UNSAFE_componentWillUpdate(d2, w, k2)), "function" === typeof g.componentDidUpdate && (b.flags |= 4), "function" === typeof g.getSnapshotBeforeUpdate && (b.flags |= 1024)) : ("function" !== typeof g.componentDidUpdate || h === a.memoizedProps && p === a.memoizedState || (b.flags |= 4), "function" !== typeof g.getSnapshotBeforeUpdate || h === a.memoizedProps && p === a.memoizedState || (b.flags |= 1024), b.memoizedProps = d2, b.memoizedState = w), g.props = d2, g.state = w, g.context = k2, d2 = l) : ("function" !== typeof g.componentDidUpdate || h === a.memoizedProps && p === a.memoizedState || (b.flags |= 4), "function" !== typeof g.getSnapshotBeforeUpdate || h === a.memoizedProps && p === a.memoizedState || (b.flags |= 1024), d2 = false);
51571
52163
  }
51572
52164
  return dg(a, b, c, d2, f, e2);
51573
52165
  }
@@ -52036,7 +52628,7 @@ var require_react_reconciler_production_min = __commonJS({
52036
52628
  case 3:
52037
52629
  c = b.stateNode;
52038
52630
  te();
52039
- q3(z63);
52631
+ q3(z68);
52040
52632
  q3(x3);
52041
52633
  ye2();
52042
52634
  c.pendingContext && (c.context = c.pendingContext, c.pendingContext = null);
@@ -52179,7 +52771,7 @@ var require_react_reconciler_production_min = __commonJS({
52179
52771
  case 1:
52180
52772
  return A(b.type) && nc(), a = b.flags, a & 65536 ? (b.flags = a & -65537 | 128, b) : null;
52181
52773
  case 3:
52182
- return te(), q3(z63), q3(x3), ye2(), a = b.flags, 0 !== (a & 65536) && 0 === (a & 128) ? (b.flags = a & -65537 | 128, b) : null;
52774
+ return te(), q3(z68), q3(x3), ye2(), a = b.flags, 0 !== (a & 65536) && 0 === (a & 128) ? (b.flags = a & -65537 | 128, b) : null;
52183
52775
  case 5:
52184
52776
  return ve2(b), null;
52185
52777
  case 13:
@@ -53234,7 +53826,7 @@ var require_react_reconciler_production_min = __commonJS({
53234
53826
  break;
53235
53827
  case 3:
53236
53828
  te();
53237
- q3(z63);
53829
+ q3(z68);
53238
53830
  q3(x3);
53239
53831
  ye2();
53240
53832
  break;
@@ -53711,7 +54303,7 @@ var require_react_reconciler_production_min = __commonJS({
53711
54303
  }
53712
54304
  var ai;
53713
54305
  ai = function(a, b, c) {
53714
- if (null !== a) if (a.memoizedProps !== b.pendingProps || z63.current) G2 = true;
54306
+ if (null !== a) if (a.memoizedProps !== b.pendingProps || z68.current) G2 = true;
53715
54307
  else {
53716
54308
  if (0 === (a.lanes & c) && 0 === (b.flags & 128)) return G2 = false, sg(a, b, c);
53717
54309
  G2 = 0 !== (a.flags & 131072) ? true : false;
@@ -53820,7 +54412,7 @@ var require_react_reconciler_production_min = __commonJS({
53820
54412
  g = e2.value;
53821
54413
  Vd(b, d2, g);
53822
54414
  if (null !== f) if (Vc(f.value, g)) {
53823
- if (f.children === e2.children && !z63.current) {
54415
+ if (f.children === e2.children && !z68.current) {
53824
54416
  b = Tf(a, b, c);
53825
54417
  break a;
53826
54418
  }
@@ -76551,10 +77143,10 @@ var init_inline2 = __esm({
76551
77143
  LinkToken = ({ label: label3, url }) => {
76552
77144
  const visibleLabel = terminalSafeText(label3, 512);
76553
77145
  const enabled = terminalHyperlinksEnabled();
76554
- const link2 = terminalHyperlinkText(visibleLabel, url, enabled);
77146
+ const link3 = terminalHyperlinkText(visibleLabel, url, enabled);
76555
77147
  const hint = formatLinkHint(url, visibleLabel.length, void 0, enabled);
76556
77148
  const linkedHint = hint ? terminalHyperlinkText(hint, url, enabled) : "";
76557
- return (0, import_jsx_runtime9.jsxs)(import_jsx_runtime9.Fragment, { children: [(0, import_jsx_runtime9.jsx)(Text, { underline: true, color: "blue", children: link2 }), (0, import_jsx_runtime9.jsx)(Text, { dimColor: true, children: linkedHint })] });
77149
+ return (0, import_jsx_runtime9.jsxs)(import_jsx_runtime9.Fragment, { children: [(0, import_jsx_runtime9.jsx)(Text, { underline: true, color: "blue", children: link3 }), (0, import_jsx_runtime9.jsx)(Text, { dimColor: true, children: linkedHint })] });
76558
77150
  };
76559
77151
  OSC_LINK = "\x1B]8;;";
76560
77152
  OSC_END = "\x1B\\";
@@ -77347,9 +77939,9 @@ function stepFold(s, e2) {
77347
77939
  }
77348
77940
  if (e2.type === "tool_result") {
77349
77941
  if (s.suppressedCallIds.has(e2.callId)) {
77350
- const scope = s.suppressedSkillScopes.get(e2.callId);
77351
- if (scope)
77352
- scope.loading = false;
77942
+ const scope2 = s.suppressedSkillScopes.get(e2.callId);
77943
+ if (scope2)
77944
+ scope2.loading = false;
77353
77945
  s.suppressedSkillScopes.delete(e2.callId);
77354
77946
  return;
77355
77947
  }
@@ -77361,9 +77953,9 @@ function stepFold(s, e2) {
77361
77953
  }
77362
77954
  if (e2.type === "tool_call_denied") {
77363
77955
  if (s.suppressedCallIds.has(e2.callId)) {
77364
- const scope = s.suppressedSkillScopes.get(e2.callId);
77365
- if (scope)
77366
- scope.loading = false;
77956
+ const scope2 = s.suppressedSkillScopes.get(e2.callId);
77957
+ if (scope2)
77958
+ scope2.loading = false;
77367
77959
  s.suppressedSkillScopes.delete(e2.callId);
77368
77960
  return;
77369
77961
  }
@@ -77810,21 +78402,21 @@ var init_SubagentScopeView = __esm({
77810
78402
  init_density();
77811
78403
  init_dist27();
77812
78404
  init_motion();
77813
- SubagentScopeView = ({ scope }) => {
78405
+ SubagentScopeView = ({ scope: scope2 }) => {
77814
78406
  const [now, setNow] = (0, import_react39.useState)(() => Date.now());
77815
- const running = scope.completedAtMs == null && scope.error == null;
78407
+ const running = scope2.completedAtMs == null && scope2.error == null;
77816
78408
  (0, import_react39.useEffect)(() => {
77817
78409
  if (!running || !MOTION_ENABLED)
77818
78410
  return;
77819
78411
  const t = setInterval(() => setNow(Date.now()), 1e3);
77820
78412
  return () => clearInterval(t);
77821
78413
  }, [running]);
77822
- const endMs = scope.completedAtMs ?? now;
77823
- const elapsed = formatElapsed(endMs - scope.startedAtMs);
77824
- const toolPart = `${scope.toolCallCount} tool call${scope.toolCallCount === 1 ? "" : "s"}`;
77825
- const dotColor = scope.error ? Colors.danger : running ? Colors.busy : DotColors.subagent;
77826
- const state = scope.error ? "failed" : running ? "running" : "done";
77827
- return (0, import_jsx_runtime18.jsxs)(Box_default, { flexDirection: "column", marginTop: blockGap(), children: [(0, import_jsx_runtime18.jsxs)(Box_default, { children: [(0, import_jsx_runtime18.jsxs)(Text, { color: dotColor, children: [Glyphs.filled, " "] }), (0, import_jsx_runtime18.jsx)(Text, { bold: true, children: `agent ` }), (0, import_jsx_runtime18.jsx)(Text, { children: scope.label }), (0, import_jsx_runtime18.jsx)(Text, { dimColor: true, children: ` ${state} ${elapsed} \xB7 ${toolPart}` })] }), scope.error ? (0, import_jsx_runtime18.jsxs)(Box_default, { marginLeft: 2, children: [(0, import_jsx_runtime18.jsx)(Text, { dimColor: true, children: "\u2514 " }), (0, import_jsx_runtime18.jsx)(Text, { color: Colors.danger, children: truncate4(scope.error, 100) })] }) : scope.finalPreview && !running ? (0, import_jsx_runtime18.jsx)(Box_default, { marginLeft: 2, children: (0, import_jsx_runtime18.jsx)(Text, { dimColor: true, children: `\u2514 ${truncate4(scope.finalPreview, 100)}` }) }) : null] });
78414
+ const endMs = scope2.completedAtMs ?? now;
78415
+ const elapsed = formatElapsed(endMs - scope2.startedAtMs);
78416
+ const toolPart = `${scope2.toolCallCount} tool call${scope2.toolCallCount === 1 ? "" : "s"}`;
78417
+ const dotColor = scope2.error ? Colors.danger : running ? Colors.busy : DotColors.subagent;
78418
+ const state = scope2.error ? "failed" : running ? "running" : "done";
78419
+ return (0, import_jsx_runtime18.jsxs)(Box_default, { flexDirection: "column", marginTop: blockGap(), children: [(0, import_jsx_runtime18.jsxs)(Box_default, { children: [(0, import_jsx_runtime18.jsxs)(Text, { color: dotColor, children: [Glyphs.filled, " "] }), (0, import_jsx_runtime18.jsx)(Text, { bold: true, children: `agent ` }), (0, import_jsx_runtime18.jsx)(Text, { children: scope2.label }), (0, import_jsx_runtime18.jsx)(Text, { dimColor: true, children: ` ${state} ${elapsed} \xB7 ${toolPart}` })] }), scope2.error ? (0, import_jsx_runtime18.jsxs)(Box_default, { marginLeft: 2, children: [(0, import_jsx_runtime18.jsx)(Text, { dimColor: true, children: "\u2514 " }), (0, import_jsx_runtime18.jsx)(Text, { color: Colors.danger, children: truncate4(scope2.error, 100) })] }) : scope2.finalPreview && !running ? (0, import_jsx_runtime18.jsx)(Box_default, { marginLeft: 2, children: (0, import_jsx_runtime18.jsx)(Text, { dimColor: true, children: `\u2514 ${truncate4(scope2.finalPreview, 100)}` }) }) : null] });
77828
78420
  };
77829
78421
  }
77830
78422
  });
@@ -77883,24 +78475,24 @@ var init_CollabScopeView = __esm({
77883
78475
  MAX_AGENTS = 8;
77884
78476
  MAX_TASKS = 6;
77885
78477
  MAX_MSGS = 6;
77886
- CollabScopeView = ({ scope }) => {
78478
+ CollabScopeView = ({ scope: scope2 }) => {
77887
78479
  const [now, setNow] = (0, import_react41.useState)(() => Date.now());
77888
- const running = scope.completedAtMs == null;
78480
+ const running = scope2.completedAtMs == null;
77889
78481
  (0, import_react41.useEffect)(() => {
77890
78482
  if (!running || !MOTION_ENABLED)
77891
78483
  return;
77892
78484
  const t = setInterval(() => setNow(Date.now()), 1e3);
77893
78485
  return () => clearInterval(t);
77894
78486
  }, [running]);
77895
- const elapsed = formatElapsed((scope.completedAtMs ?? now) - scope.startedAtMs);
77896
- const done = scope.agents.filter((a) => a.status === "done").length;
77897
- const state = running ? scope.control?.paused ? "paused" : "running" : scope.conflicts.length > 0 ? "done \xB7 conflicts" : "done";
77898
- const headColor = scope.conflicts.length > 0 ? Colors.danger : Colors.busy;
77899
- return (0, import_jsx_runtime20.jsxs)(Box_default, { flexDirection: "column", marginTop: blockGap(), children: [(0, import_jsx_runtime20.jsxs)(Box_default, { children: [(0, import_jsx_runtime20.jsxs)(Text, { color: headColor, children: [Glyphs.filled, " "] }), (0, import_jsx_runtime20.jsx)(Text, { bold: true, children: "collab " }), (0, import_jsx_runtime20.jsx)(Text, { children: truncate4(scope.task, 50) }), (0, import_jsx_runtime20.jsx)(Text, { dimColor: true, children: ` ${state} ${elapsed} \xB7 ${done}/${scope.agents.length} done` })] }), scope.fallbackReason ? (0, import_jsx_runtime20.jsx)(Box_default, { marginLeft: 2, children: (0, import_jsx_runtime20.jsx)(Text, { dimColor: true, children: `! ${truncate4(scope.fallbackReason, 90)}` }) }) : null, (0, import_jsx_runtime20.jsxs)(Box_default, { flexDirection: "column", marginLeft: 2, children: [scope.agents.slice(0, MAX_AGENTS).map((a) => {
78487
+ const elapsed = formatElapsed((scope2.completedAtMs ?? now) - scope2.startedAtMs);
78488
+ const done = scope2.agents.filter((a) => a.status === "done").length;
78489
+ const state = running ? scope2.control?.paused ? "paused" : "running" : scope2.conflicts.length > 0 ? "done \xB7 conflicts" : "done";
78490
+ const headColor = scope2.conflicts.length > 0 ? Colors.danger : Colors.busy;
78491
+ return (0, import_jsx_runtime20.jsxs)(Box_default, { flexDirection: "column", marginTop: blockGap(), children: [(0, import_jsx_runtime20.jsxs)(Box_default, { children: [(0, import_jsx_runtime20.jsxs)(Text, { color: headColor, children: [Glyphs.filled, " "] }), (0, import_jsx_runtime20.jsx)(Text, { bold: true, children: "collab " }), (0, import_jsx_runtime20.jsx)(Text, { children: truncate4(scope2.task, 50) }), (0, import_jsx_runtime20.jsx)(Text, { dimColor: true, children: ` ${state} ${elapsed} \xB7 ${done}/${scope2.agents.length} done` })] }), scope2.fallbackReason ? (0, import_jsx_runtime20.jsx)(Box_default, { marginLeft: 2, children: (0, import_jsx_runtime20.jsx)(Text, { dimColor: true, children: `! ${truncate4(scope2.fallbackReason, 90)}` }) }) : null, (0, import_jsx_runtime20.jsxs)(Box_default, { flexDirection: "column", marginLeft: 2, children: [scope2.agents.slice(0, MAX_AGENTS).map((a) => {
77900
78492
  const glyph = a.status === "done" ? "\u2713" : a.status === "working" ? "\u25CF" : a.status === "crashed" ? "\u2717" : "\u25CB";
77901
78493
  const statusProps = a.status === "working" ? { color: Colors.busy } : a.status === "crashed" ? { color: Colors.danger } : { dimColor: true };
77902
78494
  return (0, import_jsx_runtime20.jsxs)(Box_default, { children: [(0, import_jsx_runtime20.jsxs)(Text, { ...statusProps, children: [glyph, " "] }), (0, import_jsx_runtime20.jsx)(Text, { children: a.name }), (0, import_jsx_runtime20.jsx)(Text, { dimColor: true, children: ` ${a.role} \xB7 ${a.status}` })] }, a.id);
77903
- }), scope.agents.length > MAX_AGENTS ? (0, import_jsx_runtime20.jsx)(Text, { dimColor: true, children: ` +${scope.agents.length - MAX_AGENTS} more` }) : null] }), scope.tasks.length > 0 ? (0, import_jsx_runtime20.jsxs)(Box_default, { flexDirection: "column", marginLeft: 2, children: [(0, import_jsx_runtime20.jsx)(Text, { dimColor: true, children: `board (${scope.tasks.filter((t) => t.status === "done").length}/${scope.tasks.length})` }), scope.tasks.slice(0, MAX_TASKS).map((t) => (0, import_jsx_runtime20.jsx)(Text, { dimColor: true, children: ` [${t.status}] ${truncate4(t.title, 40)}${t.owner ? ` @${t.owner}` : ""}` }, t.id))] }) : null, scope.contracts.length > 0 ? (0, import_jsx_runtime20.jsx)(Box_default, { marginLeft: 2, children: (0, import_jsx_runtime20.jsx)(Text, { dimColor: true, children: `contracts: ${truncate4(scope.contracts.map((c) => c.title).join(", "), 80)}` }) }) : null, scope.messages.length > 0 ? (0, import_jsx_runtime20.jsx)(Box_default, { flexDirection: "column", marginLeft: 2, children: scope.messages.slice(-MAX_MSGS).map((m) => (0, import_jsx_runtime20.jsx)(Text, { dimColor: true, children: ` ${m.from} \u2192 ${m.to}: ${truncate4(m.body, 70)}` }, m.id)) }) : null] });
78495
+ }), scope2.agents.length > MAX_AGENTS ? (0, import_jsx_runtime20.jsx)(Text, { dimColor: true, children: ` +${scope2.agents.length - MAX_AGENTS} more` }) : null] }), scope2.tasks.length > 0 ? (0, import_jsx_runtime20.jsxs)(Box_default, { flexDirection: "column", marginLeft: 2, children: [(0, import_jsx_runtime20.jsx)(Text, { dimColor: true, children: `board (${scope2.tasks.filter((t) => t.status === "done").length}/${scope2.tasks.length})` }), scope2.tasks.slice(0, MAX_TASKS).map((t) => (0, import_jsx_runtime20.jsx)(Text, { dimColor: true, children: ` [${t.status}] ${truncate4(t.title, 40)}${t.owner ? ` @${t.owner}` : ""}` }, t.id))] }) : null, scope2.contracts.length > 0 ? (0, import_jsx_runtime20.jsx)(Box_default, { marginLeft: 2, children: (0, import_jsx_runtime20.jsx)(Text, { dimColor: true, children: `contracts: ${truncate4(scope2.contracts.map((c) => c.title).join(", "), 80)}` }) }) : null, scope2.messages.length > 0 ? (0, import_jsx_runtime20.jsx)(Box_default, { flexDirection: "column", marginLeft: 2, children: scope2.messages.slice(-MAX_MSGS).map((m) => (0, import_jsx_runtime20.jsx)(Text, { dimColor: true, children: ` ${m.from} \u2192 ${m.to}: ${truncate4(m.body, 70)}` }, m.id)) }) : null] });
77904
78496
  };
77905
78497
  }
77906
78498
  });
@@ -77959,8 +78551,8 @@ var init_ShimmerText = __esm({
77959
78551
  });
77960
78552
 
77961
78553
  // ../plugin-cli/dist/components/chat/BlockLine.js
77962
- function skillActivityPresentation(scope, childToolCount = countToolCalls(scope.children), active2 = scope.loading) {
77963
- const name = truncate4(scope.skillEvent.name, NAME_DISPLAY_MAX);
78554
+ function skillActivityPresentation(scope2, childToolCount = countToolCalls(scope2.children), active2 = scope2.loading) {
78555
+ const name = truncate4(scope2.skillEvent.name, NAME_DISPLAY_MAX);
77964
78556
  const meta = childToolCount > 0 ? `${childToolCount} tool${childToolCount === 1 ? "" : "s"}` : null;
77965
78557
  return { label: name, meta, active: active2 };
77966
78558
  }
@@ -78044,16 +78636,16 @@ var init_BlockLine = __esm({
78044
78636
  return blocksEquivalent(prev.block, next.block);
78045
78637
  }
78046
78638
  );
78047
- SkillScopeView = ({ scope, expandToolOutputs, renderVersion }) => {
78048
- const childToolCount = countToolCalls(scope.children);
78049
- const runningTools = scope.children.some(hasRunningTool);
78050
- const presentation = skillActivityPresentation(scope, childToolCount, scope.loading || !scope.closed || runningTools);
78639
+ SkillScopeView = ({ scope: scope2, expandToolOutputs, renderVersion }) => {
78640
+ const childToolCount = countToolCalls(scope2.children);
78641
+ const runningTools = scope2.children.some(hasRunningTool);
78642
+ const presentation = skillActivityPresentation(scope2, childToolCount, scope2.loading || !scope2.closed || runningTools);
78051
78643
  const hasDetails = childToolCount > 0;
78052
- const showChildren = hasDetails && (!scope.closed || runningTools || expandToolOutputs);
78053
- const failed = scope.children.some(hasFailedTool);
78054
- const dotState = scope.loading ? "neutral" : presentation.active ? "active" : failed ? "error" : "success";
78055
- const activityText = `${scope.loading ? "Loading" : presentation.active ? "Using" : failed ? "Failed" : "Used"} ${presentation.label}`;
78056
- return (0, import_jsx_runtime22.jsxs)(Box_default, { flexDirection: "column", marginTop: blockGap(), children: [(0, import_jsx_runtime22.jsxs)(Box_default, { children: [(0, import_jsx_runtime22.jsx)(ActivityDot, { state: dotState }), (0, import_jsx_runtime22.jsx)(Text, { children: " " }), (0, import_jsx_runtime22.jsx)(ShimmerText, { text: activityText, active: presentation.active }), presentation.meta ? (0, import_jsx_runtime22.jsx)(Text, { dimColor: true, children: ` \xB7 ${presentation.meta}` }) : null, scope.closed && hasDetails ? (0, import_jsx_runtime22.jsx)(Text, { dimColor: true, children: ` \xB7 Ctrl+O ${showChildren ? "collapse" : "details"}` }) : null] }), showChildren ? (0, import_jsx_runtime22.jsx)(Box_default, { flexDirection: "column", marginLeft: 2, children: scope.children.map((c) => (0, import_jsx_runtime22.jsx)(BlockLine, { block: c, expandToolOutputs, renderVersion, nested: true }, c.id)) }) : null] });
78644
+ const showChildren = hasDetails && (!scope2.closed || runningTools || expandToolOutputs);
78645
+ const failed = scope2.children.some(hasFailedTool);
78646
+ const dotState = scope2.loading ? "neutral" : presentation.active ? "active" : failed ? "error" : "success";
78647
+ const activityText = `${scope2.loading ? "Loading" : presentation.active ? "Using" : failed ? "Failed" : "Used"} ${presentation.label}`;
78648
+ return (0, import_jsx_runtime22.jsxs)(Box_default, { flexDirection: "column", marginTop: blockGap(), children: [(0, import_jsx_runtime22.jsxs)(Box_default, { children: [(0, import_jsx_runtime22.jsx)(ActivityDot, { state: dotState }), (0, import_jsx_runtime22.jsx)(Text, { children: " " }), (0, import_jsx_runtime22.jsx)(ShimmerText, { text: activityText, active: presentation.active }), presentation.meta ? (0, import_jsx_runtime22.jsx)(Text, { dimColor: true, children: ` \xB7 ${presentation.meta}` }) : null, scope2.closed && hasDetails ? (0, import_jsx_runtime22.jsx)(Text, { dimColor: true, children: ` \xB7 Ctrl+O ${showChildren ? "collapse" : "details"}` }) : null] }), showChildren ? (0, import_jsx_runtime22.jsx)(Box_default, { flexDirection: "column", marginLeft: 2, children: scope2.children.map((c) => (0, import_jsx_runtime22.jsx)(BlockLine, { block: c, expandToolOutputs, renderVersion, nested: true }, c.id)) }) : null] });
78057
78649
  };
78058
78650
  }
78059
78651
  });
@@ -81386,8 +81978,8 @@ function orderByScope(skills) {
81386
81978
  buckets.set(s.scope, list);
81387
81979
  }
81388
81980
  const out = [];
81389
- for (const scope of ORDER) {
81390
- const list = buckets.get(scope);
81981
+ for (const scope2 of ORDER) {
81982
+ const list = buckets.get(scope2);
81391
81983
  if (!list)
81392
81984
  continue;
81393
81985
  list.sort((a, b) => a.frontmatter.name.localeCompare(b.frontmatter.name));
@@ -81779,13 +82371,13 @@ var init_UsagePanel = __esm({
81779
82371
  const series = import_react58.default.useMemo(() => perCallPrompt(events), [events]);
81780
82372
  const [lifetime, setLifetime] = import_react58.default.useState(null);
81781
82373
  import_react58.default.useEffect(() => {
81782
- let alive = true;
82374
+ let alive2 = true;
81783
82375
  void loadUsageStats().then((f) => {
81784
- if (alive)
82376
+ if (alive2)
81785
82377
  setLifetime(f);
81786
82378
  });
81787
82379
  return () => {
81788
- alive = false;
82380
+ alive2 = false;
81789
82381
  };
81790
82382
  }, []);
81791
82383
  const liveByModel = import_react58.default.useMemo(() => summarizeTokensByModel(events), [events]);
@@ -84336,6 +84928,10 @@ var init_remote = __esm({
84336
84928
  // `workflows.validateDraft`, `workflows.setEnabled`) is host-only — a paired
84337
84929
  // phone must not rewrite or re-enable the host's workflows.
84338
84930
  "workflows.list",
84931
+ "workflows.approvals",
84932
+ "workflows.decideApproval",
84933
+ "workflows.revokeApproval",
84934
+ "workflows.cancelApprovalRun",
84339
84935
  "workflows.run",
84340
84936
  "workflows.getRun",
84341
84937
  // Answer a paused workflow's awaitInput question. This is RESPOND-only — like
@@ -84485,6 +85081,8 @@ var init_validation = __esm({
84485
85081
  // with an oversized string. All currently-valid payloads (a short turn id, an
84486
85082
  // optional workspace slug, an optional desk id, or no arg at all) still pass.
84487
85083
  "session.info": z.object({ workspaceId: optionalWorkspace }).optional(),
85084
+ "computer.snapshot": z.object({ workspaceId: z.string().min(1).max(160) }).strict(),
85085
+ "computer.control": computerControlCommandSchema.extend({ workspaceId: z.string().min(1).max(160) }).strict(),
84488
85086
  "session.abortTurn": z.object({
84489
85087
  workspaceId: optionalWorkspace,
84490
85088
  turnId: z.string().min(1).max(256)
@@ -84559,6 +85157,7 @@ var init_validation = __esm({
84559
85157
  }),
84560
85158
  "workflows.run": z.object({ name: workflowName }),
84561
85159
  "workflows.setEnabled": z.object({ name: workflowName, enabled: z.boolean() }),
85160
+ "workflows.delete": z.object({ name: workflowName }).strict(),
84562
85161
  // Builder commands. validateDraft/save take full YAML — bound the size so a
84563
85162
  // hostile renderer can't OOM the host; save writes to disk so it's
84564
85163
  // filesystem-touching and gets a boundary check like the other writers.
@@ -84587,6 +85186,10 @@ var init_validation = __esm({
84587
85186
  runId: z.string().min(1).max(120),
84588
85187
  reply: z.string().min(1).max(1e5)
84589
85188
  }),
85189
+ "workflows.approvals": z.object({ workspaceId: z.string().min(1) }).strict(),
85190
+ "workflows.decideApproval": z.object({ workspaceId: z.string().min(1), id: z.string().uuid(), choice: z.enum(["allow_once", "allow_always", "deny"]) }).strict(),
85191
+ "workflows.revokeApproval": z.object({ workspaceId: z.string().min(1), id: z.string().uuid() }).strict(),
85192
+ "workflows.cancelApprovalRun": z.object({ workspaceId: z.string().min(1), id: z.string().uuid() }).strict(),
84590
85193
  // Security-sensitive: this bypasses the approval sheet, so validate it at
84591
85194
  // the boundary like the other dangerous commands.
84592
85195
  "session.setAutoApprove": z.object({ workspaceId: optionalWorkspace, enabled: z.boolean() }),
@@ -85405,6 +86008,18 @@ var init_single_session_host = __esm({
85405
86008
  /** Register the `IpcCommands` subset the mobile client drives. */
85406
86009
  register() {
85407
86010
  this.bus.handle("connection.snapshotAll", async () => this.connectionSnapshots());
86011
+ const workflowApprovals = (workspaceId) => {
86012
+ if (workspaceId !== this.workspaceId)
86013
+ throw new IpcError("not-connected", "Workflow approval workspace is not served by this host");
86014
+ const view = this.session.workflows;
86015
+ if (!view?.approvals)
86016
+ throw new IpcError("not-connected", "Workflow approvals require an updated runner");
86017
+ return view.approvals;
86018
+ };
86019
+ this.bus.handle("workflows.approvals", async ({ workspaceId }) => workflowApprovals(workspaceId).list());
86020
+ this.bus.handle("workflows.decideApproval", async ({ workspaceId, id, choice }) => workflowApprovals(workspaceId).decide(id, choice));
86021
+ this.bus.handle("workflows.revokeApproval", async ({ workspaceId, id }) => workflowApprovals(workspaceId).revoke(id));
86022
+ this.bus.handle("workflows.cancelApprovalRun", async ({ workspaceId, id }) => workflowApprovals(workspaceId).cancel(id));
85408
86023
  this.bus.handle("connection.activeWorkspace", async () => this.activeWorkspaceId());
85409
86024
  this.bus.handle("connection.retry", async () => {
85410
86025
  });
@@ -91330,30 +91945,30 @@ function stringifyValue2(value2) {
91330
91945
  return value2;
91331
91946
  return JSON.stringify(value2);
91332
91947
  }
91333
- function resolveRef(ref, scope) {
91948
+ function resolveRef(ref, scope2) {
91334
91949
  const parts = ref.split(".").map((p) => p.trim());
91335
91950
  const [head2, ...rest] = parts;
91336
91951
  switch (head2) {
91337
91952
  case "trigger":
91338
- return scope.trigger ?? "";
91953
+ return scope2.trigger ?? "";
91339
91954
  case "now":
91340
- return scope.now ?? "";
91955
+ return scope2.now ?? "";
91341
91956
  case "steps": {
91342
91957
  const id = rest[0];
91343
91958
  if (!id)
91344
91959
  return void 0;
91345
- const out = scope.steps[id]?.output;
91960
+ const out = scope2.steps[id]?.output;
91346
91961
  return out ?? "";
91347
91962
  }
91348
91963
  case "inputs":
91349
- return rest[0] ? scope.inputs[rest[0]] : void 0;
91964
+ return rest[0] ? scope2.inputs[rest[0]] : void 0;
91350
91965
  case "vars":
91351
- return rest[0] ? scope.vars?.[rest[0]] : void 0;
91966
+ return rest[0] ? scope2.vars?.[rest[0]] : void 0;
91352
91967
  default:
91353
91968
  return void 0;
91354
91969
  }
91355
91970
  }
91356
- function renderTemplate(text2, scope, opts = {}) {
91971
+ function renderTemplate(text2, scope2, opts = {}) {
91357
91972
  const output = [];
91358
91973
  let cursor = 0;
91359
91974
  while (cursor < text2.length) {
@@ -91371,7 +91986,7 @@ function renderTemplate(text2, scope, opts = {}) {
91371
91986
  continue;
91372
91987
  }
91373
91988
  output.push(text2.slice(cursor, open2));
91374
- const value2 = resolveRef(ref.trim(), scope);
91989
+ const value2 = resolveRef(ref.trim(), scope2);
91375
91990
  if (value2 === void 0) {
91376
91991
  const logger = opts.logger;
91377
91992
  if (logger?.warn)
@@ -91384,15 +91999,15 @@ function renderTemplate(text2, scope, opts = {}) {
91384
91999
  output.push(text2.slice(cursor));
91385
92000
  return output.join("");
91386
92001
  }
91387
- function renderArgs(args, scope, opts = {}) {
92002
+ function renderArgs(args, scope2, opts = {}) {
91388
92003
  if (typeof args === "string")
91389
- return renderTemplate(args, scope, opts);
92004
+ return renderTemplate(args, scope2, opts);
91390
92005
  if (Array.isArray(args))
91391
- return args.map((v) => renderArgs(v, scope, opts));
92006
+ return args.map((v) => renderArgs(v, scope2, opts));
91392
92007
  if (args && typeof args === "object") {
91393
92008
  const out = {};
91394
92009
  for (const [k2, v] of Object.entries(args)) {
91395
- out[k2] = renderArgs(v, scope, opts);
92010
+ out[k2] = renderArgs(v, scope2, opts);
91396
92011
  }
91397
92012
  return out;
91398
92013
  }
@@ -91434,8 +92049,8 @@ function parseCondition(expr) {
91434
92049
  const orGroups = splitTop(trimmed, "or").map((group) => splitTop(group, "and").map(parseAtom));
91435
92050
  return { orGroups };
91436
92051
  }
91437
- function evalAtom(atom, scope) {
91438
- const value2 = renderTemplate(atom.lhs.includes("{{") ? atom.lhs : `{{ ${atom.lhs} }}`, scope).trim();
92052
+ function evalAtom(atom, scope2) {
92053
+ const value2 = renderTemplate(atom.lhs.includes("{{") ? atom.lhs : `{{ ${atom.lhs} }}`, scope2).trim();
91439
92054
  switch (atom.kind) {
91440
92055
  case "empty":
91441
92056
  return value2 === "";
@@ -91449,9 +92064,9 @@ function evalAtom(atom, scope) {
91449
92064
  return value2 !== atom.literal;
91450
92065
  }
91451
92066
  }
91452
- function evalCondition(expr, scope) {
92067
+ function evalCondition(expr, scope2) {
91453
92068
  const { orGroups } = parseCondition(expr);
91454
- return orGroups.some((group) => group.every((atom) => evalAtom(atom, scope)));
92069
+ return orGroups.some((group) => group.every((atom) => evalAtom(atom, scope2)));
91455
92070
  }
91456
92071
  function validateCondition(expr) {
91457
92072
  try {
@@ -91986,7 +92601,7 @@ async function discoverWorkflows(opts = {}) {
91986
92601
  }
91987
92602
  return [...byName.values()];
91988
92603
  }
91989
- async function loadDir2(dir, scope, logger) {
92604
+ async function loadDir2(dir, scope2, logger) {
91990
92605
  let entries;
91991
92606
  try {
91992
92607
  entries = await promises.readdir(dir, { withFileTypes: true });
@@ -91996,7 +92611,7 @@ async function loadDir2(dir, scope, logger) {
91996
92611
  const out = [];
91997
92612
  for (const entry of entries) {
91998
92613
  if (entry.isDirectory()) {
91999
- out.push(...await loadDir2(path3.join(dir, entry.name), scope, logger));
92614
+ out.push(...await loadDir2(path3.join(dir, entry.name), scope2, logger));
92000
92615
  continue;
92001
92616
  }
92002
92617
  if (!entry.isFile() || !/\.ya?ml$/i.test(entry.name))
@@ -92032,7 +92647,7 @@ async function loadDir2(dir, scope, logger) {
92032
92647
  logger.warn("workflow: invalid file, skipping", { path: full, errors: result.errors });
92033
92648
  continue;
92034
92649
  }
92035
- out.push({ workflow: result.workflow, path: full, scope });
92650
+ out.push({ workflow: result.workflow, path: full, scope: scope2 });
92036
92651
  }
92037
92652
  return out;
92038
92653
  }
@@ -92154,17 +92769,17 @@ var init_store4 = __esm({
92154
92769
  return this.byName.get(name)?.workflow;
92155
92770
  }
92156
92771
  /** Write a new workflow file and register it. Rejects duplicate names. */
92157
- async create(workflow, scope) {
92772
+ async create(workflow, scope2) {
92158
92773
  return this.mutex.run(async () => {
92159
92774
  await this.ensureLoadedUnlocked();
92160
92775
  if (this.byName.has(workflow.name)) {
92161
92776
  throw new Error(`workflow "${workflow.name}" already exists \u2014 use update instead`);
92162
92777
  }
92163
- const dir = scope === "project" ? this.projectDir() : this.userDir();
92778
+ const dir = scope2 === "project" ? this.projectDir() : this.userDir();
92164
92779
  await promises.mkdir(dir, { recursive: true });
92165
92780
  const file = await uniqueFilename(dir, workflow.name);
92166
92781
  await writeFileAtomic(file, serializeWorkflow(workflow));
92167
- const entry = { workflow, path: file, scope };
92782
+ const entry = { workflow, path: file, scope: scope2 };
92168
92783
  this.byName.set(workflow.name, entry);
92169
92784
  return entry;
92170
92785
  });
@@ -92196,12 +92811,12 @@ var init_store4 = __esm({
92196
92811
  this.byName.set(workflow.name, entry2);
92197
92812
  return entry2;
92198
92813
  }
92199
- const scope = renamed?.scope === "project" ? "project" : "user";
92200
- const dir = scope === "project" ? this.projectDir() : this.userDir();
92814
+ const scope2 = renamed?.scope === "project" ? "project" : "user";
92815
+ const dir = scope2 === "project" ? this.projectDir() : this.userDir();
92201
92816
  await promises.mkdir(dir, { recursive: true });
92202
92817
  const file = await uniqueFilename(dir, workflow.name);
92203
92818
  await writeFileAtomic(file, serializeWorkflow(workflow));
92204
- const entry = { workflow, path: file, scope };
92819
+ const entry = { workflow, path: file, scope: scope2 };
92205
92820
  this.byName.set(workflow.name, entry);
92206
92821
  return entry;
92207
92822
  }
@@ -92562,14 +93177,14 @@ var init_state_serde = __esm({
92562
93177
  init_context();
92563
93178
  }
92564
93179
  });
92565
- async function runStep(step, scope, ctx) {
93180
+ async function runStep(step, scope2, ctx) {
92566
93181
  const attempts = step.onError === "retry" ? 1 + Math.max(0, step.retries) : 1;
92567
93182
  let lastError = "";
92568
93183
  for (let attempt = 0; attempt < attempts; attempt++) {
92569
93184
  if (ctx.deps.signal.aborted)
92570
93185
  return { ok: false, output: "", error: "aborted" };
92571
93186
  try {
92572
- return await runStepOnce(step, scope, ctx);
93187
+ return await runStepOnce(step, scope2, ctx);
92573
93188
  } catch (err) {
92574
93189
  lastError = err instanceof Error ? err.message : String(err);
92575
93190
  const logger = ctx.deps.logger;
@@ -92583,28 +93198,28 @@ async function runStep(step, scope, ctx) {
92583
93198
  }
92584
93199
  return { ok: false, output: "", error: lastError };
92585
93200
  }
92586
- async function runStepOnce(step, scope, ctx) {
93201
+ async function runStepOnce(step, scope2, ctx) {
92587
93202
  const { deps } = ctx;
92588
93203
  const opts = deps.logger ? { logger: deps.logger } : {};
92589
93204
  if (step.loop != null) {
92590
93205
  return runLoopStep(step, ctx, opts);
92591
93206
  }
92592
93207
  if (step.bridge != null || step.condition != null || step.switch != null) {
92593
- return runLogicStep(step, scope, ctx, opts);
93208
+ return runLogicStep(step, scope2, ctx, opts);
92594
93209
  }
92595
93210
  if (step.echo != null) {
92596
- return { ok: true, output: renderTemplate(step.echo, scope, opts) };
93211
+ return { ok: true, output: renderTemplate(step.echo, scope2, opts) };
92597
93212
  }
92598
93213
  if (step.tool) {
92599
- const args = renderArgs(step.args ?? {}, scope, opts);
93214
+ const args = renderArgs(step.args ?? {}, scope2, opts);
92600
93215
  const result = await deps.tools.execute(step.tool, args, deps.signal);
92601
93216
  const output = typeof result === "string" ? result : JSON.stringify(result ?? "");
92602
93217
  return { ok: true, output };
92603
93218
  }
92604
93219
  if (step.workflow) {
92605
- return runNestedWorkflow(step, scope, ctx, opts);
93220
+ return runNestedWorkflow(step, scope2, ctx, opts);
92606
93221
  }
92607
- const spec = buildSubagentSpecWithDeps(step, scope, deps, opts);
93222
+ const spec = buildSubagentSpecWithDeps(step, scope2, deps, opts);
92608
93223
  if (step.awaitInput) {
92609
93224
  const child2 = await deps.spawner.spawn({ ...spec, retainSession: true });
92610
93225
  if (child2.error)
@@ -92621,7 +93236,7 @@ async function runStepOnce(step, scope, ctx) {
92621
93236
  throw new Error(child.error.message);
92622
93237
  return { ok: true, output: child.text };
92623
93238
  }
92624
- async function runNestedWorkflow(step, scope, ctx, opts) {
93239
+ async function runNestedWorkflow(step, scope2, ctx, opts) {
92625
93240
  const { deps } = ctx;
92626
93241
  assertDefined(step.workflow, "runNestedWorkflow is only invoked for workflow steps");
92627
93242
  const nested = deps.lookup.workflow(step.workflow);
@@ -92631,7 +93246,7 @@ async function runNestedWorkflow(step, scope, ctx, opts) {
92631
93246
  if (depth > MAX_NESTING_DEPTH) {
92632
93247
  throw new Error(`nested workflow depth exceeded ${MAX_NESTING_DEPTH}`);
92633
93248
  }
92634
- const nestedInputs = renderArgs(step.args ?? {}, scope, opts);
93249
+ const nestedInputs = renderArgs(step.args ?? {}, scope2, opts);
92635
93250
  const result = await ctx.runNested(nested, {
92636
93251
  ...deps,
92637
93252
  inputs: nestedInputs,
@@ -92650,11 +93265,11 @@ async function runNestedWorkflow(step, scope, ctx, opts) {
92650
93265
  throw new Error(result.error ?? `nested workflow "${step.workflow}" failed`);
92651
93266
  return { ok: true, output: result.output };
92652
93267
  }
92653
- function buildUpstreamBlock(step, scope) {
93268
+ function buildUpstreamBlock(step, scope2) {
92654
93269
  if (step.needs.length === 0)
92655
93270
  return "";
92656
93271
  const parts = step.needs.map((id) => {
92657
- const entry = scope.steps?.[id];
93272
+ const entry = scope2.steps?.[id];
92658
93273
  return `### ${id}
92659
93274
  ${entry?.output ?? ""}`;
92660
93275
  });
@@ -92663,13 +93278,13 @@ ${entry?.output ?? ""}`;
92663
93278
  ## Upstream
92664
93279
  ${parts.join("\n\n")}`;
92665
93280
  }
92666
- async function runLogicStep(step, scope, ctx, opts) {
93281
+ async function runLogicStep(step, scope2, ctx, opts) {
92667
93282
  const instruction = step.bridge ?? step.condition ?? step.switch ?? "";
92668
93283
  const format = wantsPlainResponse(step) ? "plain" : "json";
92669
93284
  if ((step.condition != null || step.switch != null) && format === "plain") {
92670
93285
  return { ok: false, output: "", error: "condition/switch steps require JSON responses" };
92671
93286
  }
92672
- const userPrompt = renderTemplate(instruction, scope, opts) + buildUpstreamBlock(step, scope);
93287
+ const userPrompt = renderTemplate(instruction, scope2, opts) + buildUpstreamBlock(step, scope2);
92673
93288
  const spec = {
92674
93289
  prompt: userPrompt,
92675
93290
  ...format === "json" ? { systemPrompt: logicSystemPrompt() } : {},
@@ -92799,8 +93414,8 @@ ${lastBodyOutput}` : "")
92799
93414
  };
92800
93415
  }
92801
93416
  async function evaluateLoopCondition(step, condition, ctx, opts) {
92802
- const scope = buildScope(ctx, new Date(ctx.now()).toISOString());
92803
- const userPrompt = renderTemplate(condition, scope, opts) + `
93417
+ const scope2 = buildScope(ctx, new Date(ctx.now()).toISOString());
93418
+ const userPrompt = renderTemplate(condition, scope2, opts) + `
92804
93419
 
92805
93420
  This is the loop's EXIT condition. Evaluate whether it is now met. Reply with {"branch":"then"} if the condition IS met (stop the loop and continue to the next step), or {"branch":"else"} if it is NOT yet met (run another iteration).`;
92806
93421
  const spec = {
@@ -92827,9 +93442,9 @@ This is the loop's EXIT condition. Evaluate whether it is now met. Reply with {"
92827
93442
  return { ok: false, error: err instanceof Error ? err.message : String(err) };
92828
93443
  }
92829
93444
  }
92830
- function buildSubagentSpecWithDeps(step, scope, deps, opts) {
93445
+ function buildSubagentSpecWithDeps(step, scope2, deps, opts) {
92831
93446
  const label3 = step.label ?? step.id;
92832
- const renderedInput = step.input ? renderTemplate(step.input, scope, opts) : "";
93447
+ const renderedInput = step.input ? renderTemplate(step.input, scope2, opts) : "";
92833
93448
  if (step.skill) {
92834
93449
  const skill = deps.lookup.skill(step.skill);
92835
93450
  if (!skill)
@@ -92845,7 +93460,7 @@ function buildSubagentSpecWithDeps(step, scope, deps, opts) {
92845
93460
  spec.allowedTools = allowed;
92846
93461
  return spec;
92847
93462
  }
92848
- return { prompt: renderTemplate(step.prompt ?? "", scope, opts), label: label3 };
93463
+ return { prompt: renderTemplate(step.prompt ?? "", scope2, opts), label: label3 };
92849
93464
  }
92850
93465
  var init_steps = __esm({
92851
93466
  "../plugin-workflows/dist/executor/steps.js"() {
@@ -92885,10 +93500,10 @@ async function runExecutorLoop(ctx, resumed = false) {
92885
93500
  continue;
92886
93501
  if (step.when == null)
92887
93502
  continue;
92888
- const scope2 = buildScope(ctx, new Date(ctx.now()).toISOString());
93503
+ const scope3 = buildScope(ctx, new Date(ctx.now()).toISOString());
92889
93504
  let keep;
92890
93505
  try {
92891
- keep = evalCondition(step.when, scope2);
93506
+ keep = evalCondition(step.when, scope3);
92892
93507
  } catch (err) {
92893
93508
  st3.status = "failed";
92894
93509
  st3.error = `when: ${err instanceof Error ? err.message : String(err)}`;
@@ -92929,9 +93544,9 @@ async function runExecutorLoop(ctx, resumed = false) {
92929
93544
  break;
92930
93545
  }
92931
93546
  const wave = ready.slice(0, Math.max(1, workflow.concurrency));
92932
- const scope = buildScope(ctx, new Date(ctx.now()).toISOString());
93547
+ const scope2 = buildScope(ctx, new Date(ctx.now()).toISOString());
92933
93548
  for (const step of wave) {
92934
- if (aborted)
93549
+ if (aborted || deps.signal.aborted)
92935
93550
  break;
92936
93551
  const st3 = ctx.states.get(step.id);
92937
93552
  assertDefined(st3, "runExecutor initializes a state for every step");
@@ -92940,8 +93555,14 @@ async function runExecutorLoop(ctx, resumed = false) {
92940
93555
  id: step.id,
92941
93556
  label: step.label ?? step.id
92942
93557
  });
92943
- const outcome = await runStep(step, scope, ctx);
93558
+ const outcome = await runStep(step, scope2, ctx);
92944
93559
  st3.endedAt = ctx.now();
93560
+ if (deps.signal.aborted) {
93561
+ st3.status = "cancelled";
93562
+ st3.output = outcome.output;
93563
+ await deps.emit?.("workflow_step_cancelled", { id: step.id });
93564
+ break;
93565
+ }
92945
93566
  if (outcome.paused) {
92946
93567
  const interactionAgentId = outcome.interactionAgentId;
92947
93568
  assertDefined(interactionAgentId, "a paused outcome always carries interactionAgentId");
@@ -93007,6 +93628,10 @@ async function runExecutorLoop(ctx, resumed = false) {
93007
93628
  }
93008
93629
  const ok = !aborted;
93009
93630
  const output = sinkOutput(workflow, ctx.states);
93631
+ if (deps.signal.aborted) {
93632
+ await deps.emit?.("workflow_cancelled", { name: workflow.name });
93633
+ return buildRunResult(ctx, "cancelled", false, { output });
93634
+ }
93010
93635
  if (ok) {
93011
93636
  await deps.emit?.("workflow_completed", {
93012
93637
  name: workflow.name,
@@ -93102,11 +93727,13 @@ async function resumeWorkflowRunInner(runId, userMessage, deps, store) {
93102
93727
  const finalizePrompt = `Operator reply:
93103
93728
  ${userMessage.trim()}${FINALIZE_REPLY_SUFFIX}`;
93104
93729
  try {
93730
+ deps.signal.throwIfAborted();
93105
93731
  const child = await deps.spawner.continue({
93106
93732
  childSessionId: checkpoint.interactionAgentId,
93107
93733
  prompt: finalizePrompt,
93108
93734
  label: step.label ?? step.id
93109
93735
  });
93736
+ deps.signal.throwIfAborted();
93110
93737
  if (child.error)
93111
93738
  throw new Error(child.error.message);
93112
93739
  st3.status = "completed";
@@ -93117,6 +93744,14 @@ ${userMessage.trim()}${FINALIZE_REPLY_SUFFIX}`;
93117
93744
  preview: child.text.slice(0, 280)
93118
93745
  });
93119
93746
  } catch (err) {
93747
+ if (deps.signal.aborted) {
93748
+ st3.status = "cancelled";
93749
+ st3.endedAt = ctx.now();
93750
+ await store.remove(runId);
93751
+ await deps.emit?.("workflow_step_cancelled", { id: step.id });
93752
+ await deps.emit?.("workflow_cancelled", { runId, name: checkpoint.workflow.name });
93753
+ return buildRunResult(ctx, "cancelled", false, { runId });
93754
+ }
93120
93755
  const message = err instanceof Error ? err.message : String(err);
93121
93756
  st3.status = "failed";
93122
93757
  st3.error = message;
@@ -93205,6 +93840,7 @@ async function writeRunRecord2(workflow, result, startedAt, executorName, deps,
93205
93840
  startedAt,
93206
93841
  trigger: deps.trigger ?? "manual",
93207
93842
  ok: result.ok,
93843
+ status: result.status,
93208
93844
  ...result.error ? { error: result.error } : {}
93209
93845
  }),
93210
93846
  ...result.steps.map((s) => JSON.stringify({ kind: "step", ...s })),
@@ -93461,7 +94097,7 @@ function buildRunDeps(deps, ctx, inputs, trigger) {
93461
94097
  }) : void 0;
93462
94098
  return {
93463
94099
  spawner: ctx.subagents,
93464
- tools: deps.tools,
94100
+ tools: deps.toolsForTurn ? deps.toolsForTurn(ctx) : deps.tools,
93465
94101
  lookup: {
93466
94102
  skill: (n) => deps.skills.byName(n),
93467
94103
  workflow: (n) => deps.store.lookup(n)
@@ -93515,7 +94151,7 @@ function createTool(deps) {
93515
94151
  timeMs: 12e4
93516
94152
  }
93517
94153
  },
93518
- handler: async ({ intent, scope }, ctx) => {
94154
+ handler: async ({ intent, scope: scope2 }, ctx) => {
93519
94155
  const provider = deps.provider?.();
93520
94156
  if (!provider) {
93521
94157
  throw new MoxxyError({ code: "PROVIDER_NOT_CONFIGURED", message: "workflow_create: no active provider to draft with." });
@@ -93532,8 +94168,8 @@ function createTool(deps) {
93532
94168
  message: drafted.truncated ? "workflow_create: the draft hit the output-token limit before the YAML was complete. Try a simpler intent, or split the workflow into smaller ones." : `workflow_create: the model did not produce a valid workflow (${drafted.parse.errors.join("; ")}). Try a more specific intent.`
93533
94169
  });
93534
94170
  }
93535
- const created = await deps.store.create(drafted.parse.workflow, scope);
93536
- emitChange(deps, ctx, "workflow_created", { name: created.workflow.name, scope });
94171
+ const created = await deps.store.create(drafted.parse.workflow, scope2);
94172
+ emitChange(deps, ctx, "workflow_created", { name: created.workflow.name, scope: scope2 });
93537
94173
  await deps.onChanged?.();
93538
94174
  return { name: created.workflow.name, scope: created.scope, path: created.path, steps: created.workflow.steps.length };
93539
94175
  }
@@ -93611,7 +94247,7 @@ function deleteTool(deps) {
93611
94247
  if (!res.ok)
93612
94248
  throw new MoxxyError({ code: "TOOL_ERROR", message: `workflow_delete: ${res.reason}.` });
93613
94249
  emitChange(deps, ctx, "workflow_deleted", { name });
93614
- await deps.onChanged?.();
94250
+ await deps.onChanged?.(name);
93615
94251
  return { name, deleted: true };
93616
94252
  }
93617
94253
  });
@@ -93651,11 +94287,15 @@ function runTool(deps) {
93651
94287
  message: "workflow_run: no subagent spawner \u2014 must be invoked from a run-turn loop."
93652
94288
  });
93653
94289
  }
93654
- const runDeps = buildRunDeps(deps, { sessionId: ctx.sessionId, turnId: ctx.turnId, signal: ctx.signal, subagents: ctx.subagents }, inputs, "manual");
93655
- const result = await runWorkflow(entry.workflow, runDeps, {
93656
- executor: deps.getActiveExecutor(),
93657
- ...deps.runRecordDir !== void 0 ? { recordDir: deps.runRecordDir } : {}
93658
- });
94290
+ const spawner = ctx.subagents;
94291
+ const execute = (signal = ctx.signal) => {
94292
+ const runDeps = buildRunDeps(deps, { sessionId: ctx.sessionId, turnId: ctx.turnId, signal, subagents: deps.subagentsForTurn ? deps.subagentsForTurn(ctx.turnId, signal) : spawner }, inputs, "manual");
94293
+ return runWorkflow(entry.workflow, runDeps, {
94294
+ executor: deps.getActiveExecutor(),
94295
+ ...deps.runRecordDir !== void 0 ? { recordDir: deps.runRecordDir } : {}
94296
+ });
94297
+ };
94298
+ const result = await (deps.runScoped ? deps.runScoped(name, ctx, execute, entry.workflow) : execute());
93659
94299
  return {
93660
94300
  ok: result.ok,
93661
94301
  output: result.output,
@@ -93848,7 +94488,7 @@ async function runCmd2(deps, name) {
93848
94488
  ].filter((l) => l !== "");
93849
94489
  return { kind: "text", text: lines.join("\n") };
93850
94490
  }
93851
- const head2 = result.ok ? `\u2713 workflow "${name}" completed` : `\u2717 workflow "${name}" failed${result.error ? `: ${result.error}` : ""}`;
94491
+ const head2 = result.status === "cancelled" ? `\u25A0 workflow "${name}" stopped` : result.ok ? `\u2713 workflow "${name}" completed` : `\u2717 workflow "${name}" failed${result.error ? `: ${result.error}` : ""}`;
93852
94492
  return { kind: "text", text: `${head2}
93853
94493
  ${steps}
93854
94494
 
@@ -93924,11 +94564,11 @@ async function rmCmd(deps, name) {
93924
94564
  const res = await deps.store.delete(name);
93925
94565
  if (!res.ok)
93926
94566
  return { kind: "error", message: `cannot delete "${name}": ${res.reason}.` };
93927
- await deps.onChanged?.();
94567
+ await deps.onChanged?.(name);
93928
94568
  return { kind: "text", text: `deleted workflow "${name}".` };
93929
94569
  }
93930
94570
  function statusMark(status) {
93931
- return status === "completed" ? "\u2713" : status === "skipped" ? "\u2013" : status === "failed" ? "\u2717" : "\xB7";
94571
+ return status === "cancelled" ? "\u25A0" : status === "completed" ? "\u2713" : status === "skipped" ? "\u2013" : status === "failed" ? "\u2717" : "\xB7";
93932
94572
  }
93933
94573
  async function readLastRun(dir, name) {
93934
94574
  if (!dir)
@@ -93948,7 +94588,7 @@ async function readLastRun(dir, name) {
93948
94588
  if (run2?.workflow !== name)
93949
94589
  continue;
93950
94590
  const steps = lines.filter((l) => l.kind === "step");
93951
- const head2 = `${run2.ok ? "\u2713" : "\u2717"} ${new Date(Number(run2.startedAt ?? 0)).toISOString()} (${String(run2.trigger ?? "?")})`;
94591
+ const head2 = `${run2.status === "cancelled" ? "\u25A0 stopped" : run2.ok ? "\u2713" : "\u2717"} ${new Date(Number(run2.startedAt ?? 0)).toISOString()} (${String(run2.trigger ?? "?")})`;
93952
94592
  const stepLines = steps.map((s) => ` ${statusMark(String(s.status))} ${String(s.id)}`).join("\n");
93953
94593
  return `${head2}
93954
94594
  ${stepLines}`;
@@ -94022,6 +94662,9 @@ function buildWorkflowsPlugin(opts) {
94022
94662
  store: opts.store,
94023
94663
  skills: opts.skills,
94024
94664
  tools: opts.tools,
94665
+ ...opts.toolsForTurn ? { toolsForTurn: opts.toolsForTurn } : {},
94666
+ ...opts.runScoped ? { runScoped: opts.runScoped } : {},
94667
+ ...opts.subagentsForTurn ? { subagentsForTurn: opts.subagentsForTurn } : {},
94025
94668
  getActiveExecutor: opts.getActiveExecutor,
94026
94669
  ...opts.appendEvent ? { appendEvent: opts.appendEvent } : {},
94027
94670
  ...opts.logger ? { logger: opts.logger } : {},
@@ -94093,7 +94736,13 @@ function buildWorkflowRunner(args) {
94093
94736
  async function runNow(input) {
94094
94737
  const entry = await store.get(input.name);
94095
94738
  if (!entry) {
94096
- return { ok: false, status: "failed", steps: [], output: "", error: `no workflow named "${input.name}"` };
94739
+ return {
94740
+ ok: false,
94741
+ status: "failed",
94742
+ steps: [],
94743
+ output: "",
94744
+ error: `no workflow named "${input.name}"`
94745
+ };
94097
94746
  }
94098
94747
  if (inFlight.has(input.name)) {
94099
94748
  return {
@@ -94106,41 +94755,49 @@ function buildWorkflowRunner(args) {
94106
94755
  }
94107
94756
  inFlight.add(input.name);
94108
94757
  try {
94758
+ const parentSignal = input.signal ? AbortSignal.any([session.signal, input.signal]) : session.signal;
94759
+ parentSignal.throwIfAborted();
94109
94760
  const turnId = session.startTurn().turnId;
94110
- const spawner = createSubagentSpawner({
94111
- parentSession: session,
94112
- parentTurnId: turnId,
94113
- parentSignal: session.signal,
94114
- parentModel: activeModel(session)
94115
- });
94116
- const result = await runWorkflow(
94117
- entry.workflow,
94118
- {
94119
- spawner,
94120
- tools: session.tools,
94121
- lookup: {
94122
- skill: (n) => session.skills.byName(n),
94123
- workflow: (n) => store.lookup(n)
94761
+ const execute = (signal = parentSignal) => {
94762
+ const spawner = createSubagentSpawner({
94763
+ parentSession: session,
94764
+ parentTurnId: turnId,
94765
+ parentSignal: signal,
94766
+ parentModel: input.model ?? activeModel(session)
94767
+ });
94768
+ return runWorkflow(
94769
+ entry.workflow,
94770
+ {
94771
+ spawner,
94772
+ tools: createWorkflowToolRunner(session, turnId, spawner),
94773
+ lookup: {
94774
+ skill: (n) => session.skills.byName(n),
94775
+ workflow: (n) => store.lookup(n)
94776
+ },
94777
+ signal,
94778
+ ...input.inputs ? { inputs: input.inputs } : {},
94779
+ trigger: input.trigger ?? "auto",
94780
+ now: () => Date.now(),
94781
+ emit: (subtype, payload2) => void session.log.append({
94782
+ type: "plugin_event",
94783
+ sessionId: session.id,
94784
+ turnId,
94785
+ source: "plugin",
94786
+ pluginId: PLUGIN_ID3,
94787
+ subtype,
94788
+ // Stamp the causal chain onto the completion event so the
94789
+ // afterWorkflow subscription can detect cycles/depth per-run.
94790
+ payload: subtype === "workflow_completed" && input.chain && input.chain.length > 0 ? { ...payload2, triggerChain: [...input.chain] } : payload2
94791
+ }),
94792
+ ...logger ? { logger } : {}
94124
94793
  },
94125
- signal: session.signal,
94126
- ...input.inputs ? { inputs: input.inputs } : {},
94127
- trigger: input.trigger ?? "auto",
94128
- now: () => Date.now(),
94129
- emit: (subtype, payload2) => void session.log.append({
94130
- type: "plugin_event",
94131
- sessionId: session.id,
94132
- turnId,
94133
- source: "plugin",
94134
- pluginId: PLUGIN_ID3,
94135
- subtype,
94136
- // Stamp the causal chain onto the completion event so the
94137
- // afterWorkflow subscription can detect cycles/depth per-run.
94138
- payload: subtype === "workflow_completed" && input.chain && input.chain.length > 0 ? { ...payload2, triggerChain: [...input.chain] } : payload2
94139
- }),
94140
- ...logger ? { logger } : {}
94141
- },
94142
- { executor: session.workflowExecutors.getActive() }
94143
- );
94794
+ {
94795
+ executor: session.workflowExecutors.getActive(),
94796
+ ...args.recordDir ? { recordDir: args.recordDir } : {}
94797
+ }
94798
+ );
94799
+ };
94800
+ const result = await (args.approvalExecution ? args.approvalExecution.run(input.name, String(turnId), parentSignal, execute, entry.workflow) : execute());
94144
94801
  if (result.status === "paused") {
94145
94802
  logger?.warn?.("workflows: run paused awaiting operator input; not delivering to inbox", {
94146
94803
  workflow: input.name,
@@ -94156,8 +94813,7 @@ function buildWorkflowRunner(args) {
94156
94813
  }
94157
94814
  async function resumeNow(runId, reply) {
94158
94815
  const checkpoint = await defaultWorkflowRunStore.load(runId);
94159
- const name = checkpoint?.workflow?.name;
94160
- if (!name) {
94816
+ if (!checkpoint || !checkpoint.workflow.name) {
94161
94817
  return {
94162
94818
  ok: false,
94163
94819
  status: "failed",
@@ -94166,6 +94822,7 @@ function buildWorkflowRunner(args) {
94166
94822
  error: `no resumable run "${runId}"`
94167
94823
  };
94168
94824
  }
94825
+ const name = checkpoint.workflow.name;
94169
94826
  if (inFlight.has(name)) {
94170
94827
  return {
94171
94828
  ok: false,
@@ -94178,41 +94835,47 @@ function buildWorkflowRunner(args) {
94178
94835
  inFlight.add(name);
94179
94836
  try {
94180
94837
  const turnId = session.startTurn().turnId;
94181
- const spawner = createSubagentSpawner({
94182
- parentSession: session,
94183
- parentTurnId: turnId,
94184
- parentSignal: session.signal,
94185
- parentModel: activeModel(session)
94186
- });
94187
- const result = await resumeWorkflowRun(
94188
- runId,
94189
- reply,
94190
- {
94191
- spawner,
94192
- tools: session.tools,
94193
- lookup: {
94194
- skill: (n) => session.skills.byName(n),
94195
- workflow: (n) => store.lookup(n)
94838
+ const execute = (signal = session.signal) => {
94839
+ const spawner = createSubagentSpawner({
94840
+ parentSession: session,
94841
+ parentTurnId: turnId,
94842
+ parentSignal: signal,
94843
+ parentModel: activeModel(session)
94844
+ });
94845
+ return resumeWorkflowRun(
94846
+ runId,
94847
+ reply,
94848
+ {
94849
+ spawner,
94850
+ tools: createWorkflowToolRunner(session, turnId, spawner),
94851
+ lookup: {
94852
+ skill: (n) => session.skills.byName(n),
94853
+ workflow: (n) => store.lookup(n)
94854
+ },
94855
+ signal,
94856
+ now: () => Date.now(),
94857
+ emit: (subtype, payload2) => void session.log.append({
94858
+ type: "plugin_event",
94859
+ sessionId: session.id,
94860
+ turnId,
94861
+ source: "plugin",
94862
+ pluginId: PLUGIN_ID3,
94863
+ subtype,
94864
+ payload: payload2
94865
+ }),
94866
+ ...logger ? { logger } : {}
94196
94867
  },
94197
- signal: session.signal,
94198
- now: () => Date.now(),
94199
- emit: (subtype, payload2) => void session.log.append({
94200
- type: "plugin_event",
94201
- sessionId: session.id,
94202
- turnId,
94203
- source: "plugin",
94204
- pluginId: PLUGIN_ID3,
94205
- subtype,
94206
- payload: payload2
94207
- }),
94208
- ...logger ? { logger } : {}
94209
- },
94210
- defaultWorkflowRunStore
94211
- );
94868
+ defaultWorkflowRunStore
94869
+ );
94870
+ };
94871
+ const result = await (args.approvalExecution ? args.approvalExecution.run(name, String(turnId), session.signal, execute, checkpoint.workflow) : execute());
94212
94872
  if (result.status === "paused") {
94213
- logger?.warn?.("workflows: run paused again awaiting operator input; not delivering to inbox", {
94214
- runId: result.runId
94215
- });
94873
+ logger?.warn?.(
94874
+ "workflows: run paused again awaiting operator input; not delivering to inbox",
94875
+ {
94876
+ runId: result.runId
94877
+ }
94878
+ );
94216
94879
  return result;
94217
94880
  }
94218
94881
  await deliverToInbox(checkpoint.workflow, result, logger);
@@ -94246,7 +94909,7 @@ async function deliverToInbox(workflow, result, logger) {
94246
94909
  `workflow: ${workflow.name}`,
94247
94910
  `firedAt: ${(/* @__PURE__ */ new Date()).toISOString()}`,
94248
94911
  workflow.delivery?.channel ? `channel: ${workflow.delivery.channel}` : null,
94249
- `outcome: ${result.ok ? "ok" : "error"}`,
94912
+ `outcome: ${result.status === "cancelled" ? "cancelled" : result.ok ? "ok" : "error"}`,
94250
94913
  "---",
94251
94914
  ""
94252
94915
  ].filter((l) => l !== null).join("\n");
@@ -94281,6 +94944,11 @@ function triggerSummary2(on) {
94281
94944
  function buildWorkflowsView(args) {
94282
94945
  const { store, runner, syncSchedules } = args;
94283
94946
  return {
94947
+ delete: async (name) => {
94948
+ const result = await store.delete(name);
94949
+ if (!result.ok) throw new Error(`Cannot delete workflow: ${result.reason}`);
94950
+ await syncSchedules(name);
94951
+ },
94284
94952
  list: async () => (await store.list()).map((w) => ({
94285
94953
  name: w.workflow.name,
94286
94954
  description: w.workflow.description,
@@ -94350,6 +95018,104 @@ var init_build_workflow_tools = __esm({
94350
95018
  init_dist35();
94351
95019
  }
94352
95020
  });
95021
+ function definition(workflow, store, visited = /* @__PURE__ */ new Set()) {
95022
+ if (visited.has(workflow.name)) return { cycle: workflow.name };
95023
+ visited.add(workflow.name);
95024
+ const {
95025
+ name: _name,
95026
+ description: _description,
95027
+ on: _on,
95028
+ enabled: _enabled,
95029
+ ...execution
95030
+ } = workflow;
95031
+ return {
95032
+ execution,
95033
+ nested: workflow.steps.filter((step) => step.workflow).map((step) => {
95034
+ const nested = step.workflow ? store.lookup(step.workflow) : void 0;
95035
+ return nested ? definition(nested, store, visited) : null;
95036
+ })
95037
+ };
95038
+ }
95039
+ function buildWorkflowApprovalExecution(cwd2, store, approvalDir = join(moxxyPath("workflow-approvals"), approvalFingerprint(cwd2))) {
95040
+ const approvals = new WorkflowApprovals(approvalDir);
95041
+ const current = new AsyncLocalStorage();
95042
+ const active2 = /* @__PURE__ */ new Map();
95043
+ return {
95044
+ approvals,
95045
+ execution: {
95046
+ async run(name, runId, signal, task, expectedDefinition) {
95047
+ await store.load();
95048
+ const entry = await store.get(name);
95049
+ if (!entry || !entry.workflow.enabled) throw new Error("Workflow is missing or disabled");
95050
+ const revision = approvalFingerprint(definition(entry.workflow, store));
95051
+ if (expectedDefinition && approvalFingerprint(definition(expectedDefinition, store)) !== revision)
95052
+ throw new Error("Workflow definition changed; reload before starting or resuming it");
95053
+ const workflowId = approvalFingerprint([cwd2, entry.path]);
95054
+ const inherited = current.getStore();
95055
+ if (inherited && inherited.scope.workflowId === workflowId)
95056
+ return task(AbortSignal.any([signal, inherited.signal]));
95057
+ if (active2.has(workflowId))
95058
+ throw new Error(
95059
+ "Workflow execution skipped: another execution is running or awaiting approval"
95060
+ );
95061
+ const release = await claimWorkflowLease(join(approvalDir, "leases"), workflowId, signal);
95062
+ try {
95063
+ const scope2 = { workflowId, workflowName: name, revision, runId };
95064
+ const controller = new AbortController();
95065
+ const effectiveSignal = AbortSignal.any([signal, controller.signal]);
95066
+ active2.set(workflowId, runId);
95067
+ const valid = async () => {
95068
+ if (await approvals.isCancelled(scope2)) controller.abort("Workflow stopped");
95069
+ await store.load();
95070
+ const updated = await store.get(name);
95071
+ return !effectiveSignal.aborted && !!updated && updated.workflow.enabled && approvalFingerprint(definition(updated.workflow, store)) === revision;
95072
+ };
95073
+ let checking = false;
95074
+ const timer = setInterval(() => {
95075
+ if (checking) return;
95076
+ checking = true;
95077
+ void valid().then((ok) => {
95078
+ if (!ok) controller.abort("Workflow changed or stopped");
95079
+ }).catch((error) => controller.abort(error)).finally(() => {
95080
+ checking = false;
95081
+ });
95082
+ }, 200);
95083
+ timer.unref();
95084
+ try {
95085
+ return await current.run(
95086
+ { scope: scope2, signal: effectiveSignal },
95087
+ () => withPermissionScope(
95088
+ {
95089
+ name: "workflow-scoped-approval",
95090
+ check: async (call) => {
95091
+ if (!await valid())
95092
+ return { mode: "deny", reason: "Workflow changed, disabled or cancelled" };
95093
+ const decision = await approvals.check(scope2, call, effectiveSignal, valid);
95094
+ if (await approvals.isCancelled(scope2)) controller.abort("Workflow stopped");
95095
+ return decision;
95096
+ }
95097
+ },
95098
+ () => task(effectiveSignal)
95099
+ )
95100
+ );
95101
+ } finally {
95102
+ clearInterval(timer);
95103
+ controller.abort("Workflow ended");
95104
+ active2.delete(workflowId);
95105
+ await approvals.finishRun(runId);
95106
+ }
95107
+ } finally {
95108
+ await release();
95109
+ }
95110
+ }
95111
+ }
95112
+ };
95113
+ }
95114
+ var init_workflow_approval_scope = __esm({
95115
+ "src/setup/workflow-approval-scope.ts"() {
95116
+ init_dist2();
95117
+ }
95118
+ });
94353
95119
  function detectAfterWorkflowCycles(workflows) {
94354
95120
  const enabled = /* @__PURE__ */ new Map();
94355
95121
  for (const w of workflows) if (w.enabled) enabled.set(w.name, w);
@@ -94535,7 +95301,14 @@ function wireWorkflowTriggers(args) {
94535
95301
  }
94536
95302
  }
94537
95303
  }
94538
- async function syncSchedules() {
95304
+ async function syncSchedules(deletedName) {
95305
+ if (deletedName) {
95306
+ for (const entry of await scheduleStore.list()) {
95307
+ if (entry.source === "workflow" && entry.workflowName === deletedName) {
95308
+ await scheduleStore.delete(entry.id);
95309
+ }
95310
+ }
95311
+ }
94539
95312
  const all = await store.list();
94540
95313
  applyAfterWorkflowCycleGuard({
94541
95314
  workflows: all.map((w) => w.workflow),
@@ -94654,7 +95427,10 @@ function buildWorkflowsIntegration(args) {
94654
95427
  builtinDir: BUILTIN_WORKFLOWS_DIR,
94655
95428
  ...logger ? { logger } : {}
94656
95429
  });
94657
- const runner = buildWorkflowRunner({ session, store, ...logger ? { logger } : {} });
95430
+ const { approvals, execution } = buildWorkflowApprovalExecution(session.cwd, store);
95431
+ session.services.register("workflowApprovalExecution", execution);
95432
+ const runner = buildWorkflowRunner({ session, store, approvalExecution: execution, ...logger ? { logger } : {} });
95433
+ session.services.register("workflowRunner", runner);
94658
95434
  const fileLock = ownerSessionId ? new CrossProcessFireLock({ dir: moxxyPath("locks", "workflow-triggers"), ttlMs: 3e3 }) : void 0;
94659
95435
  const triggers = wireWorkflowTriggers({
94660
95436
  session,
@@ -94667,11 +95443,19 @@ function buildWorkflowsIntegration(args) {
94667
95443
  ...ownerSessionId ? { thisRunnerSessionId: ownerSessionId } : {},
94668
95444
  ...logger ? { logger } : {}
94669
95445
  });
94670
- const view = buildWorkflowsView({ store, runner, syncSchedules: triggers.syncSchedules });
95446
+ const view = { ...buildWorkflowsView({ store, runner, syncSchedules: triggers.syncSchedules }), approvals };
94671
95447
  const built = buildWorkflowsPlugin({
94672
95448
  store,
94673
95449
  skills: session.skills,
94674
95450
  tools: session.tools,
95451
+ toolsForTurn: (ctx) => createWorkflowToolRunner(session, ctx.turnId, ctx.subagents),
95452
+ runScoped: (name, ctx, task, definition2) => execution.run(name, String(ctx.turnId), ctx.signal, task, definition2),
95453
+ subagentsForTurn: (turnId, signal) => createSubagentSpawner({
95454
+ parentSession: session,
95455
+ parentTurnId: turnId,
95456
+ parentSignal: signal,
95457
+ parentModel: activeModel(session)
95458
+ }),
94675
95459
  getActiveExecutor: () => session.workflowExecutors.getActive(),
94676
95460
  appendEvent: (e2) => session.log.append(e2),
94677
95461
  ...logger ? { logger } : {},
@@ -94715,6 +95499,7 @@ var init_workflows2 = __esm({
94715
95499
  init_dist35();
94716
95500
  init_build_workflow_runner();
94717
95501
  init_build_workflow_tools();
95502
+ init_workflow_approval_scope();
94718
95503
  init_wire_run_store();
94719
95504
  }
94720
95505
  });
@@ -94977,25 +95762,45 @@ var init_builtins = __esm({
94977
95762
  // src/setup/scheduler-runner.ts
94978
95763
  function buildSchedulerRunner(session) {
94979
95764
  return {
94980
- runPrompt: async ({ prompt, model, origin }) => {
94981
- let text2 = "";
94982
- let lastError = null;
94983
- try {
94984
- for await (const event of runTurn(session, prompt, {
94985
- ...origin ? { origin } : {},
94986
- ...model ? { model } : {}
94987
- })) {
94988
- if (event.type === "assistant_message") {
94989
- text2 = event.content;
94990
- lastError = event.stopReason === "error" ? "turn ended with error stop reason" : null;
94991
- } else if (event.type === "error") {
94992
- lastError = event.message;
94993
- }
95765
+ runPrompt: async ({ prompt, model, origin, signal }) => {
95766
+ if (origin?.kind === "workflow") {
95767
+ const runner = session.services.get("workflowRunner");
95768
+ if (!runner) return { text: "", error: "Workflow runner is not ready" };
95769
+ try {
95770
+ const result = await runner.runNow({
95771
+ name: origin.name,
95772
+ trigger: "schedule",
95773
+ ...model ? { model } : {},
95774
+ ...signal ? { signal } : {}
95775
+ });
95776
+ return { text: result.output, ...result.status === "cancelled" ? { cancelled: true } : {}, ...result.error ? { error: result.error } : {} };
95777
+ } catch (error) {
95778
+ return { text: "", error: error instanceof Error ? error.message : String(error) };
94994
95779
  }
94995
- } catch (err) {
94996
- return { text: text2, error: err instanceof Error ? err.message : String(err) };
94997
95780
  }
94998
- return lastError ? { text: text2, error: lastError } : { text: text2 };
95781
+ const turnId = session.startTurn().turnId;
95782
+ const execute = async () => {
95783
+ let text2 = "";
95784
+ let lastError = null;
95785
+ try {
95786
+ for await (const event of runTurn(session, prompt, {
95787
+ turnId,
95788
+ ...origin ? { origin } : {},
95789
+ ...model ? { model } : {}
95790
+ })) {
95791
+ if (event.type === "assistant_message") {
95792
+ text2 = event.content;
95793
+ lastError = event.stopReason === "error" ? "turn ended with error stop reason" : null;
95794
+ } else if (event.type === "error") {
95795
+ lastError = event.message;
95796
+ }
95797
+ }
95798
+ } catch (err) {
95799
+ return { text: text2, error: err instanceof Error ? err.message : String(err) };
95800
+ }
95801
+ return lastError ? { text: text2, error: lastError } : { text: text2 };
95802
+ };
95803
+ return execute();
94999
95804
  }
95000
95805
  };
95001
95806
  }
@@ -95782,7 +96587,7 @@ function _t(t, e2) {
95782
96587
  return { lines: n, numLinesBefore: s.length, numLinesAfter: i.length, numLines: r };
95783
96588
  }
95784
96589
  function Ct(t) {
95785
- return t === z58;
96590
+ return t === z63;
95786
96591
  }
95787
96592
  function T(t, e2) {
95788
96593
  const s = t;
@@ -95826,7 +96631,7 @@ function Dt(t, e2) {
95826
96631
  function St(t, e2) {
95827
96632
  if (e2) return t ? e2 : e2[0];
95828
96633
  }
95829
- var import_picocolors, import_sisteransi, at, lt, ht, O, y, L, P, M, ct, ft, X, pt, S, W, Z, Ft, j, Q, dt, tt, U, et, mt, st, it, gt, G, vt, Et, At, _, bt, z58, rt, nt, x, Vt, kt, yt, Lt, Mt, Wt, Tt, $t;
96634
+ var import_picocolors, import_sisteransi, at, lt, ht, O, y, L, P, M, ct, ft, X, pt, S, W, Z, Ft, j, Q, dt, tt, U, et, mt, st, it, gt, G, vt, Et, At, _, bt, z63, rt, nt, x, Vt, kt, yt, Lt, Mt, Wt, Tt, $t;
95830
96635
  var init_dist36 = __esm({
95831
96636
  "../../node_modules/.pnpm/@clack+core@1.0.1/node_modules/@clack/core/dist/index.mjs"() {
95832
96637
  import_picocolors = __toESM(require_picocolors());
@@ -95993,7 +96798,7 @@ var init_dist36 = __esm({
95993
96798
  At = ["up", "down", "left", "right", "space", "enter", "cancel"];
95994
96799
  _ = { actions: new Set(At), aliases: /* @__PURE__ */ new Map([["k", "up"], ["j", "down"], ["h", "left"], ["l", "right"], ["", "cancel"], ["escape", "cancel"]]), messages: { cancel: "Canceled", error: "Something went wrong" }, withGuide: true };
95995
96800
  bt = globalThis.process.platform.startsWith("win");
95996
- z58 = /* @__PURE__ */ Symbol("clack:cancel");
96801
+ z63 = /* @__PURE__ */ Symbol("clack:cancel");
95997
96802
  rt = (t) => "columns" in t && typeof t.columns == "number" ? t.columns : 80;
95998
96803
  nt = (t) => "rows" in t && typeof t.rows == "number" ? t.rows : 20;
95999
96804
  x = class {
@@ -96036,7 +96841,7 @@ var init_dist36 = __esm({
96036
96841
  prompt() {
96037
96842
  return new Promise((e2) => {
96038
96843
  if (this._abortSignal) {
96039
- if (this._abortSignal.aborted) return this.state = "cancel", this.close(), e2(z58);
96844
+ if (this._abortSignal.aborted) return this.state = "cancel", this.close(), e2(z63);
96040
96845
  this._abortSignal.addEventListener("abort", () => {
96041
96846
  this.state = "cancel", this.close();
96042
96847
  }, { once: true });
@@ -96044,7 +96849,7 @@ var init_dist36 = __esm({
96044
96849
  this.rl = k__default.createInterface({ input: this.input, tabSize: 2, prompt: "", escapeCodeTimeout: 50, terminal: true }), this.rl.prompt(), this.opts.initialUserInput !== void 0 && this._setUserInput(this.opts.initialUserInput, true), this.input.on("keypress", this.onKeypress), T(this.input, true), this.output.on("resize", this.render), this.render(), this.once("submit", () => {
96045
96850
  this.output.write(import_sisteransi.cursor.show), this.output.off("resize", this.render), T(this.input, false), e2(this.value);
96046
96851
  }), this.once("cancel", () => {
96047
- this.output.write(import_sisteransi.cursor.show), this.output.off("resize", this.render), T(this.input, false), e2(z58);
96852
+ this.output.write(import_sisteransi.cursor.show), this.output.off("resize", this.render), T(this.input, false), e2(z63);
96048
96853
  });
96049
96854
  });
96050
96855
  }
@@ -101267,9 +102072,9 @@ async function runConfigCommand(argv) {
101267
102072
  return 0;
101268
102073
  }
101269
102074
  const sub = argv.positional[0];
101270
- const scope = stringFlag(argv, "scope") ?? "user";
101271
- if (scope !== "user" && scope !== "project") {
101272
- printError(`invalid --scope: ${scope} (use user|project)`);
102075
+ const scope2 = stringFlag(argv, "scope") ?? "user";
102076
+ if (scope2 !== "user" && scope2 !== "project") {
102077
+ printError(`invalid --scope: ${scope2} (use user|project)`);
101273
102078
  return 2;
101274
102079
  }
101275
102080
  switch (sub) {
@@ -101302,7 +102107,7 @@ async function runConfigCommand(argv) {
101302
102107
  }
101303
102108
  try {
101304
102109
  const res = await setConfigValue({
101305
- scope,
102110
+ scope: scope2,
101306
102111
  cwd: process.cwd(),
101307
102112
  path: dotPath,
101308
102113
  value: parseValue2(raw)
@@ -105478,10 +106283,10 @@ async function runSkillsCommand(argv) {
105478
106283
  const usedCol = Math.max(4, ...skills.map((s) => usedFor(s).length));
105479
106284
  for (const s of skills) {
105480
106285
  const name = colors.bold(s.frontmatter.name.padEnd(nameCol));
105481
- const scope = colors.dim(s.scope.padEnd(scopeCol));
106286
+ const scope2 = colors.dim(s.scope.padEnd(scopeCol));
105482
106287
  const used = colors.dim(usedFor(s).padStart(usedCol));
105483
106288
  const desc = colors.dim(s.frontmatter.description);
105484
- process.stdout.write(`${name} ${scope} ${used} ${desc}
106289
+ process.stdout.write(`${name} ${scope2} ${used} ${desc}
105485
106290
  `);
105486
106291
  }
105487
106292
  return 0;
@@ -106560,7 +107365,7 @@ async function waitForChannelStatus(name, def) {
106560
107365
  while (Date.now() < deadline) {
106561
107366
  const status = liveChannelStatus(name);
106562
107367
  if (status && (!needsUrl || status.requestUrl)) return status;
106563
- await delay(POLL_MS2);
107368
+ await delay3(POLL_MS2);
106564
107369
  }
106565
107370
  return liveChannelStatus(name);
106566
107371
  }
@@ -106568,7 +107373,7 @@ async function waitForChannelGone(name) {
106568
107373
  const deadline = Date.now() + STOP_GRACE_MS2;
106569
107374
  while (Date.now() < deadline) {
106570
107375
  if (!liveChannelStatus(name)) return true;
106571
- await delay(POLL_MS2);
107376
+ await delay3(POLL_MS2);
106572
107377
  }
106573
107378
  return liveChannelStatus(name) === null;
106574
107379
  }
@@ -106611,7 +107416,7 @@ function formatSubcommandHelp(channelName, subName, sub) {
106611
107416
  lines.push(` ${colors.dim(sub.description)}`);
106612
107417
  return lines.join("\n") + "\n";
106613
107418
  }
106614
- var HELP20, START_TIMEOUT_MS2, STOP_GRACE_MS2, POLL_MS2, delay;
107419
+ var HELP20, START_TIMEOUT_MS2, STOP_GRACE_MS2, POLL_MS2, delay3;
106615
107420
  var init_channels2 = __esm({
106616
107421
  async "src/commands/channels.ts"() {
106617
107422
  await init_argv_helpers();
@@ -106641,7 +107446,7 @@ var init_channels2 = __esm({
106641
107446
  START_TIMEOUT_MS2 = 15e3;
106642
107447
  STOP_GRACE_MS2 = 4e3;
106643
107448
  POLL_MS2 = 300;
106644
- delay = (ms) => new Promise((r) => setTimeout(r, ms));
107449
+ delay3 = (ms) => new Promise((r) => setTimeout(r, ms));
106645
107450
  }
106646
107451
  });
106647
107452