@codelia/runtime 0.1.84 → 0.1.85

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.
@@ -13,7 +13,6 @@ import {
13
13
  appendPermissionAllowRules,
14
14
  appendReadMetadata,
15
15
  assertExpectedContentHash,
16
- assertUltrafastAuth,
17
16
  buildConfiguredModelRegistry,
18
17
  buildSystemPermissions,
19
18
  clipUtf8,
@@ -87,7 +86,7 @@ import {
87
86
  updateModel,
88
87
  updateTuiTheme,
89
88
  withRpcResponseContext
90
- } from "./chunk-JR6IMNTT.js";
89
+ } from "./chunk-V5WO2QTA.js";
91
90
 
92
91
  // src/runtime.ts
93
92
  import {
@@ -1401,9 +1400,9 @@ var excerptByBytes = (value, maxBytes) => {
1401
1400
  if (maxBytes <= markerBytes + 2) {
1402
1401
  return truncateUtf8Prefix(value, maxBytes);
1403
1402
  }
1404
- const budget = maxBytes - markerBytes;
1405
- const headBytes = Math.floor(budget / 2);
1406
- const tailBytes = budget - headBytes;
1403
+ const budget2 = maxBytes - markerBytes;
1404
+ const headBytes = Math.floor(budget2 / 2);
1405
+ const tailBytes = budget2 - headBytes;
1407
1406
  return `${truncateUtf8Prefix(value, headBytes)}${marker}${truncateUtf8Suffix(value, tailBytes)}`;
1408
1407
  };
1409
1408
  var needsInlineTruncation = (value) => value.split(/\r?\n/).length > DEFAULT_EXCERPT_LINES * 2 || utf8ByteLength(value) > MAX_INLINE_OUTPUT_BYTES;
@@ -1953,14 +1952,14 @@ async function exportImageBytes(workspaceRoot, outputPath, bytes, mediaType = "i
1953
1952
  throw new ImageGenerationError(
1954
1953
  "Image export path must match the original PNG or JPEG format in this workspace."
1955
1954
  );
1956
- const target = path3.resolve(workspaceRoot, outputPath);
1955
+ const target2 = path3.resolve(workspaceRoot, outputPath);
1957
1956
  try {
1958
1957
  const root = await realpath(workspaceRoot);
1959
- const parent = await realpath(path3.dirname(target));
1958
+ const parent = await realpath(path3.dirname(target2));
1960
1959
  const relative = path3.relative(root, parent);
1961
1960
  if (relative === ".." || relative.startsWith(`..${path3.sep}`) || path3.isAbsolute(relative))
1962
1961
  throw new Error("outside workspace");
1963
- const destination = path3.join(parent, path3.basename(target));
1962
+ const destination = path3.join(parent, path3.basename(target2));
1964
1963
  const file = await open(destination, "wx", 384);
1965
1964
  try {
1966
1965
  await file.writeFile(bytes);
@@ -2324,15 +2323,15 @@ async function downloadImageSource(value, callerSignal, transport = requestImage
2324
2323
  async function readImageFile(sandbox, filePath, signal) {
2325
2324
  try {
2326
2325
  signal?.throwIfAborted();
2327
- const target = await realpath2(sandbox.resolvePath(filePath));
2326
+ const target2 = await realpath2(sandbox.resolvePath(filePath));
2328
2327
  if (sandbox.approvalMode !== "full-access") {
2329
2328
  const root = await realpath2(sandbox.rootDir);
2330
- const relative = path5.relative(root, target);
2329
+ const relative = path5.relative(root, target2);
2331
2330
  if (relative === ".." || relative.startsWith(`..${path5.sep}`) || path5.isAbsolute(relative))
2332
2331
  throw new Error("outside sandbox");
2333
2332
  }
2334
2333
  const handle = await open2(
2335
- target,
2334
+ target2,
2336
2335
  constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0)
2337
2336
  );
2338
2337
  try {
@@ -3796,9 +3795,9 @@ var excerptByBytes2 = (value, maxBytes) => {
3796
3795
  truncated: true
3797
3796
  };
3798
3797
  }
3799
- const budget = maxBytes - markerBytes;
3800
- const headBytes = Math.floor(budget / 2);
3801
- const tailBytes = budget - headBytes;
3798
+ const budget2 = maxBytes - markerBytes;
3799
+ const headBytes = Math.floor(budget2 / 2);
3800
+ const tailBytes = budget2 - headBytes;
3802
3801
  return {
3803
3802
  text: `${truncateUtf8Prefix2(value, headBytes)}${marker}${truncateUtf8Suffix2(value, tailBytes)}`,
3804
3803
  truncated: true
@@ -4965,10 +4964,10 @@ var VolatileRunEventStoreFactory = class {
4965
4964
  var VolatileToolOutputCacheStore = class {
4966
4965
  records = /* @__PURE__ */ new Map();
4967
4966
  async save(record) {
4968
- const id = record.tool_call_id;
4969
- this.records.set(id, structuredClone(record));
4967
+ const id2 = record.tool_call_id;
4968
+ this.records.set(id2, structuredClone(record));
4970
4969
  return {
4971
- id,
4970
+ id: id2,
4972
4971
  byte_size: Buffer.byteLength(record.content, "utf8"),
4973
4972
  line_count: record.content.split(/\r?\n/).length
4974
4973
  };
@@ -6871,17 +6870,17 @@ var LaneManager = class {
6871
6870
  "zellij backend is not supported yet in lane MVP. Use tmux."
6872
6871
  );
6873
6872
  }
6874
- async startTmuxLane(target, worktreePath, seedContext) {
6873
+ async startTmuxLane(target2, worktreePath, seedContext) {
6875
6874
  const launchCommand = this.buildLaunchCommand(seedContext);
6876
6875
  await this.cmd("tmux", [
6877
6876
  "new-session",
6878
6877
  "-d",
6879
6878
  "-s",
6880
- target,
6879
+ target2,
6881
6880
  "-c",
6882
6881
  worktreePath
6883
6882
  ]);
6884
- const paneTarget = `${target}:0.0`;
6883
+ const paneTarget = `${target2}:0.0`;
6885
6884
  await this.cmd("tmux", [
6886
6885
  "send-keys",
6887
6886
  "-t",
@@ -6902,9 +6901,9 @@ var LaneManager = class {
6902
6901
  }
6903
6902
  return `${this.launchCommand} ${INITIAL_MESSAGE_FLAG} ${this.shellQuote(seed)}`;
6904
6903
  }
6905
- async isTmuxAlive(target) {
6904
+ async isTmuxAlive(target2) {
6906
6905
  try {
6907
- await this.cmd("tmux", ["has-session", "-t", target], {
6906
+ await this.cmd("tmux", ["has-session", "-t", target2], {
6908
6907
  timeoutMs: 5e3
6909
6908
  });
6910
6909
  return true;
@@ -6916,9 +6915,9 @@ var LaneManager = class {
6916
6915
  );
6917
6916
  }
6918
6917
  }
6919
- async stopTmuxLane(target) {
6918
+ async stopTmuxLane(target2) {
6920
6919
  try {
6921
- await this.cmd("tmux", ["kill-session", "-t", target], {
6920
+ await this.cmd("tmux", ["kill-session", "-t", target2], {
6922
6921
  timeoutMs: 1e4
6923
6922
  });
6924
6923
  } catch (error) {
@@ -7419,8 +7418,8 @@ var createReadTool = (sandboxKey) => defineTool9({
7419
7418
  if (bytes + size > MAX_BYTES) {
7420
7419
  if (outputLines.length === 0) {
7421
7420
  const prefix = `${String(index + 1).padStart(5, " ")} `;
7422
- const budget = MAX_BYTES - Buffer.byteLength(prefix, "utf8");
7423
- const clippedByBytes = clipLineToByteBudget(line, budget);
7421
+ const budget2 = MAX_BYTES - Buffer.byteLength(prefix, "utf8");
7422
+ const clippedByBytes = clipLineToByteBudget(line, budget2);
7424
7423
  if (clippedByBytes.length > 0) {
7425
7424
  outputLines.push(clippedByBytes);
7426
7425
  bytes = Buffer.byteLength(`${prefix}${clippedByBytes}`, "utf8");
@@ -8560,7 +8559,7 @@ var withPatchApplied = (currentTodos, updates) => {
8560
8559
  id: normalizeTodoId(update.id)
8561
8560
  }));
8562
8561
  const currentIds = new Set(currentTodos.map((todo) => todo.id));
8563
- const missingIds = normalizedUpdates.map((update) => update.id).filter((id) => !currentIds.has(id));
8562
+ const missingIds = normalizedUpdates.map((update) => update.id).filter((id2) => !currentIds.has(id2));
8564
8563
  if (missingIds.length > 0) {
8565
8564
  const knownIds = currentTodos.map((todo) => todo.id);
8566
8565
  return {
@@ -9464,9 +9463,9 @@ var waitForTaskOrMessage = async (coordinator, owner, taskId, signal) => {
9464
9463
  // src/tools/task.ts
9465
9464
  var createSubagentTaskTools = (coordinator, ownerSession, spawn6) => {
9466
9465
  const session = () => {
9467
- const id = ownerSession();
9468
- if (!id) throw new Error("No parent session");
9469
- return id;
9466
+ const id2 = ownerSession();
9467
+ if (!id2) throw new Error("No parent session");
9468
+ return id2;
9470
9469
  };
9471
9470
  const idSchema = z28.object({
9472
9471
  task_id: z28.string().min(1).describe(
@@ -10227,9 +10226,9 @@ var AttachmentTransferService = class {
10227
10226
  "Attachment upload staging is full; retry or cancel an unused upload"
10228
10227
  );
10229
10228
  }
10230
- const id = createAttachmentId();
10229
+ const id2 = createAttachmentId();
10231
10230
  const upload = {
10232
- id,
10231
+ id: id2,
10233
10232
  key: params.upload_key,
10234
10233
  sessionId,
10235
10234
  name: name2,
@@ -10240,10 +10239,10 @@ var AttachmentTransferService = class {
10240
10239
  expires: this.now() + this.limits.lease_ms,
10241
10240
  pins: 0
10242
10241
  };
10243
- this.uploads.set(id, upload);
10242
+ this.uploads.set(id2, upload);
10244
10243
  this.stagedBytes += upload.size;
10245
10244
  processStagedBytes += upload.size;
10246
- return { upload_id: id, offset: 0 };
10245
+ return { upload_id: id2, offset: 0 };
10247
10246
  });
10248
10247
  }
10249
10248
  async chunk(params, sessionId) {
@@ -10325,13 +10324,13 @@ var AttachmentTransferService = class {
10325
10324
  async resolveForAdmission(ids, sessionId, options) {
10326
10325
  return this.serial(async () => {
10327
10326
  const result = [];
10328
- for (const id of ids) {
10327
+ for (const id2 of ids) {
10329
10328
  const upload = this.eligibleUpload(
10330
- id,
10329
+ id2,
10331
10330
  sessionId,
10332
10331
  options?.allowDraft ?? false
10333
10332
  );
10334
- const record = upload?.record ?? await this.lookup(id, sessionId);
10333
+ const record = upload?.record ?? await this.lookup(id2, sessionId);
10335
10334
  if (!record)
10336
10335
  throw new AttachmentUploadError(
10337
10336
  "Attachment unavailable in this session; re-upload to retry"
@@ -10346,16 +10345,16 @@ var AttachmentTransferService = class {
10346
10345
  return this.serial(async () => {
10347
10346
  const pending = [];
10348
10347
  const entries = [];
10349
- for (const id of new Set(ids)) {
10348
+ for (const id2 of new Set(ids)) {
10350
10349
  const upload = this.eligibleUpload(
10351
- id,
10350
+ id2,
10352
10351
  sessionId,
10353
10352
  options?.allowDraft ?? false
10354
10353
  );
10355
10354
  if (upload?.bytes && upload.record) {
10356
10355
  pending.push(upload);
10357
10356
  entries.push({ record: upload.record, bytes: upload.bytes });
10358
- } else if (!await this.lookup(id, sessionId)) {
10357
+ } else if (!await this.lookup(id2, sessionId)) {
10359
10358
  throw new AttachmentUploadError(
10360
10359
  "Attachment unavailable in this session; re-upload to retry"
10361
10360
  );
@@ -10382,10 +10381,10 @@ var AttachmentTransferService = class {
10382
10381
  async pin(ids, sessionId) {
10383
10382
  return this.serial(async () => {
10384
10383
  const pinned = [];
10385
- for (const id of new Set(ids)) {
10386
- const upload = this.eligibleUpload(id, sessionId, false);
10384
+ for (const id2 of new Set(ids)) {
10385
+ const upload = this.eligibleUpload(id2, sessionId, false);
10387
10386
  if (upload?.bytes && upload.record) pinned.push(upload);
10388
- else if (!await this.lookup(id, sessionId))
10387
+ else if (!await this.lookup(id2, sessionId))
10389
10388
  throw new AttachmentUploadError(
10390
10389
  "Attachment unavailable in this session; re-upload to retry"
10391
10390
  );
@@ -10399,12 +10398,12 @@ var AttachmentTransferService = class {
10399
10398
  };
10400
10399
  });
10401
10400
  }
10402
- async read(id, sessionId, offset, length) {
10401
+ async read(id2, sessionId, offset, length) {
10403
10402
  try {
10404
- if (!isAttachmentId(id) || !Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(length) || length < 0 || length > DEFAULT_LIMITS.max_chunk_bytes) {
10403
+ if (!isAttachmentId(id2) || !Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(length) || length < 0 || length > DEFAULT_LIMITS.max_chunk_bytes) {
10405
10404
  throw new Error("Invalid attachment byte range");
10406
10405
  }
10407
- const bytes = await this.store.read(id, sessionId, offset, length);
10406
+ const bytes = await this.store.read(id2, sessionId, offset, length);
10408
10407
  if (bytes.length > length)
10409
10408
  throw new Error("Attachment adapter exceeded the requested byte range");
10410
10409
  return bytes;
@@ -10414,9 +10413,9 @@ var AttachmentTransferService = class {
10414
10413
  );
10415
10414
  }
10416
10415
  }
10417
- async lookup(id, sessionId) {
10416
+ async lookup(id2, sessionId) {
10418
10417
  try {
10419
- return isAttachmentId(id) ? await this.store.lookup(id, sessionId) : null;
10418
+ return isAttachmentId(id2) ? await this.store.lookup(id2, sessionId) : null;
10420
10419
  } catch {
10421
10420
  throw new AttachmentUploadError(
10422
10421
  "Attachment original is missing, corrupt or unavailable in this session"
@@ -10461,8 +10460,8 @@ var AttachmentTransferService = class {
10461
10460
  );
10462
10461
  }
10463
10462
  }
10464
- getUpload(id, sessionId) {
10465
- const upload = this.uploads.get(id);
10463
+ getUpload(id2, sessionId) {
10464
+ const upload = this.uploads.get(id2);
10466
10465
  if (!upload || upload.sessionId !== sessionId) {
10467
10466
  throw new AttachmentUploadError(
10468
10467
  "Attachment upload expired or is unavailable in this session"
@@ -10477,8 +10476,8 @@ var AttachmentTransferService = class {
10477
10476
  );
10478
10477
  }
10479
10478
  }
10480
- eligibleUpload(id, sessionId, allowDraft) {
10481
- const upload = this.uploads.get(id);
10479
+ eligibleUpload(id2, sessionId, allowDraft) {
10480
+ const upload = this.uploads.get(id2);
10482
10481
  if (!upload?.bytes || !upload.record) return void 0;
10483
10482
  const owner = upload.sessionId;
10484
10483
  return owner === sessionId || owner === null && allowDraft ? upload : void 0;
@@ -10607,8 +10606,8 @@ var matchesRequestId = (value, expectedRequestId) => {
10607
10606
  return value.some((entry) => matchesRequestId(entry, expectedRequestId));
10608
10607
  }
10609
10608
  if (!isRecord4(value)) return false;
10610
- const id = value.id;
10611
- return typeof id === "string" || typeof id === "number" ? String(id) === expectedRequestId : false;
10609
+ const id2 = value.id;
10610
+ return typeof id2 === "string" || typeof id2 === "number" ? String(id2) === expectedRequestId : false;
10612
10611
  };
10613
10612
  var readSseBody = async (response, expectedRequestId) => {
10614
10613
  if (!expectedRequestId) {
@@ -11462,8 +11461,8 @@ var createMcpToolAdapter = (params) => {
11462
11461
  var OAUTH_TOKEN_EXPIRY_SKEW_MS = 6e4;
11463
11462
  var nowIso3 = () => (/* @__PURE__ */ new Date()).toISOString();
11464
11463
  var describeError2 = (error) => error instanceof Error ? error.message : String(error);
11465
- var toListServer = (id, runtime) => ({
11466
- id,
11464
+ var toListServer = (id2, runtime) => ({
11465
+ id: id2,
11467
11466
  transport: runtime.config.transport,
11468
11467
  source: runtime.config.source,
11469
11468
  enabled: runtime.config.enabled,
@@ -11511,7 +11510,7 @@ var McpManager = class {
11511
11510
  );
11512
11511
  }
11513
11512
  list(scope = "loaded") {
11514
- const servers = Array.from(this.servers.entries()).map(([id, runtime]) => toListServer(id, runtime)).sort((left, right) => left.id.localeCompare(right.id));
11513
+ const servers = Array.from(this.servers.entries()).map(([id2, runtime]) => toListServer(id2, runtime)).sort((left, right) => left.id.localeCompare(right.id));
11515
11514
  if (scope === "configured") {
11516
11515
  return { servers };
11517
11516
  }
@@ -11885,7 +11884,7 @@ var McpManager = class {
11885
11884
 
11886
11885
  // src/rpc/handlers.ts
11887
11886
  import {
11888
- RPC_ERROR_CODE as RPC_ERROR_CODE17
11887
+ RPC_ERROR_CODE as RPC_ERROR_CODE18
11889
11888
  } from "@codelia/protocol";
11890
11889
  import {
11891
11890
  RunEventStoreFactoryImpl,
@@ -11899,7 +11898,7 @@ var PROTOCOL_VERSION = "0";
11899
11898
 
11900
11899
  // src/rpc/attachment.ts
11901
11900
  import { RPC_ERROR_CODE } from "@codelia/protocol";
11902
- async function handleAttachmentUpload(state, id, method, params) {
11901
+ async function handleAttachmentUpload(state, id2, method, params) {
11903
11902
  const attachments = state.attachments;
11904
11903
  try {
11905
11904
  if (!attachments)
@@ -11911,7 +11910,7 @@ async function handleAttachmentUpload(state, id, method, params) {
11911
11910
  switch (method) {
11912
11911
  case "attachment.upload.begin":
11913
11912
  return sendResult(
11914
- id,
11913
+ id2,
11915
11914
  await attachments.begin(
11916
11915
  params,
11917
11916
  state.sessionId
@@ -11919,7 +11918,7 @@ async function handleAttachmentUpload(state, id, method, params) {
11919
11918
  );
11920
11919
  case "attachment.upload.chunk":
11921
11920
  return sendResult(
11922
- id,
11921
+ id2,
11923
11922
  await attachments.chunk(
11924
11923
  params,
11925
11924
  state.sessionId
@@ -11927,7 +11926,7 @@ async function handleAttachmentUpload(state, id, method, params) {
11927
11926
  );
11928
11927
  case "attachment.upload.finish":
11929
11928
  return sendResult(
11930
- id,
11929
+ id2,
11931
11930
  await attachments.finish(
11932
11931
  params.upload_id,
11933
11932
  state.sessionId
@@ -11938,13 +11937,13 @@ async function handleAttachmentUpload(state, id, method, params) {
11938
11937
  params.upload_id,
11939
11938
  state.sessionId
11940
11939
  );
11941
- return sendResult(id, {
11940
+ return sendResult(id2, {
11942
11941
  ok: true
11943
11942
  });
11944
11943
  }
11945
11944
  } catch (error) {
11946
11945
  if (!(error instanceof AttachmentUploadError)) throw error;
11947
- sendError(id, {
11946
+ sendError(id2, {
11948
11947
  code: RPC_ERROR_CODE.INVALID_PARAMS,
11949
11948
  message: error.message
11950
11949
  });
@@ -11955,9 +11954,9 @@ async function handleAttachmentUpload(state, id, method, params) {
11955
11954
  import {
11956
11955
  RPC_ERROR_CODE as RPC_ERROR_CODE2
11957
11956
  } from "@codelia/protocol";
11958
- var createAuthLogoutHandler = ({ state, log: log2 }) => async (id, params) => {
11957
+ var createAuthLogoutHandler = ({ state, log: log2 }) => async (id2, params) => {
11959
11958
  if (state.activeRunId) {
11960
- sendError(id, {
11959
+ sendError(id2, {
11961
11960
  code: RPC_ERROR_CODE2.RUNTIME_BUSY,
11962
11961
  message: "runtime busy"
11963
11962
  });
@@ -11965,14 +11964,14 @@ var createAuthLogoutHandler = ({ state, log: log2 }) => async (id, params) => {
11965
11964
  }
11966
11965
  const provider = params?.provider;
11967
11966
  if (params?.confirmed !== void 0 && typeof params.confirmed !== "boolean") {
11968
- sendError(id, {
11967
+ sendError(id2, {
11969
11968
  code: RPC_ERROR_CODE2.INVALID_PARAMS,
11970
11969
  message: "confirmed must be a boolean"
11971
11970
  });
11972
11971
  return;
11973
11972
  }
11974
11973
  if (provider !== void 0 && (typeof provider !== "string" || !/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/.test(provider))) {
11975
- sendError(id, {
11974
+ sendError(id2, {
11976
11975
  code: RPC_ERROR_CODE2.INVALID_PARAMS,
11977
11976
  message: "invalid logout provider name"
11978
11977
  });
@@ -11990,7 +11989,7 @@ var createAuthLogoutHandler = ({ state, log: log2 }) => async (id, params) => {
11990
11989
  if (hostAuth) {
11991
11990
  const credentials = state.effectiveEnvironment.adapters.credentialProvider;
11992
11991
  if (provider ? !credentials?.clearProviderAuth : !credentials?.clearAuth) {
11993
- sendError(id, {
11992
+ sendError(id2, {
11994
11993
  code: RPC_ERROR_CODE2.RUNTIME_INTERNAL,
11995
11994
  message: provider ? "host auth provider does not support scoped logout" : "host auth provider does not support logout"
11996
11995
  });
@@ -12003,7 +12002,7 @@ var createAuthLogoutHandler = ({ state, log: log2 }) => async (id, params) => {
12003
12002
  if (provider) {
12004
12003
  const auth = await store.load();
12005
12004
  if (!Object.hasOwn(auth.providers, provider) && !configuredProviders(config?.providers).includes(provider)) {
12006
- sendError(id, {
12005
+ sendError(id2, {
12007
12006
  code: RPC_ERROR_CODE2.INVALID_PARAMS,
12008
12007
  message: `unknown logout provider: ${provider}`
12009
12008
  });
@@ -12012,7 +12011,7 @@ var createAuthLogoutHandler = ({ state, log: log2 }) => async (id, params) => {
12012
12011
  }
12013
12012
  const preconfirmed = params?.confirmed === true;
12014
12013
  if (!preconfirmed && !state.uiCapabilities?.supports_confirm) {
12015
- sendError(id, {
12014
+ sendError(id2, {
12016
12015
  code: RPC_ERROR_CODE2.RUNTIME_INTERNAL,
12017
12016
  message: "UI confirmation is required for logout"
12018
12017
  });
@@ -12028,7 +12027,7 @@ var createAuthLogoutHandler = ({ state, log: log2 }) => async (id, params) => {
12028
12027
  allow_reason: false
12029
12028
  });
12030
12029
  if (!confirm?.ok) {
12031
- sendResult(id, {
12030
+ sendResult(id2, {
12032
12031
  ok: false,
12033
12032
  auth_cleared: false,
12034
12033
  session_cleared: false,
@@ -12053,7 +12052,7 @@ var createAuthLogoutHandler = ({ state, log: log2 }) => async (id, params) => {
12053
12052
  state.sessionAppend = null;
12054
12053
  state.sessionModelOverride = null;
12055
12054
  }
12056
- sendResult(id, {
12055
+ sendResult(id2, {
12057
12056
  ok: true,
12058
12057
  auth_cleared: true,
12059
12058
  session_cleared: clearSession,
@@ -12063,7 +12062,7 @@ var createAuthLogoutHandler = ({ state, log: log2 }) => async (id, params) => {
12063
12062
  `auth.logout provider=${provider ?? "all"} session_cleared=${clearSession}`
12064
12063
  );
12065
12064
  } catch {
12066
- sendError(id, {
12065
+ sendError(id2, {
12067
12066
  code: RPC_ERROR_CODE2.RUNTIME_INTERNAL,
12068
12067
  message: "auth logout failed"
12069
12068
  });
@@ -12099,9 +12098,9 @@ var saveProviderAuth = async (provider, auth) => {
12099
12098
  var createAuthManagementHandlers = ({ state, log: log2 }) => {
12100
12099
  let pending = null;
12101
12100
  let loginSeq = 0;
12102
- const rejectUnsupported = (id) => {
12101
+ const rejectUnsupported = (id2) => {
12103
12102
  if (supportsAuthManagement(state)) return false;
12104
- sendError(id, {
12103
+ sendError(id2, {
12105
12104
  code: RPC_ERROR_CODE3.INVALID_PARAMS,
12106
12105
  message: "auth is host-owned"
12107
12106
  });
@@ -12160,11 +12159,11 @@ var createAuthManagementHandlers = ({ state, log: log2 }) => {
12160
12159
  );
12161
12160
  return { config, providers: uniqueProviders(config.providers) };
12162
12161
  };
12163
- const handleStatus = async (id, params) => {
12164
- if (rejectUnsupported(id)) return;
12162
+ const handleStatus = async (id2, params) => {
12163
+ if (rejectUnsupported(id2)) return;
12165
12164
  const requested = params?.provider;
12166
12165
  if (requested !== void 0 && (typeof requested !== "string" || !PROVIDER_NAME_PATTERN.test(requested))) {
12167
- sendError(id, {
12166
+ sendError(id2, {
12168
12167
  code: RPC_ERROR_CODE3.INVALID_PARAMS,
12169
12168
  message: "invalid provider name"
12170
12169
  });
@@ -12173,7 +12172,7 @@ var createAuthManagementHandlers = ({ state, log: log2 }) => {
12173
12172
  try {
12174
12173
  const { config, providers } = await resolveProviders();
12175
12174
  if (requested !== void 0 && !providers.includes(requested)) {
12176
- sendError(id, {
12175
+ sendError(id2, {
12177
12176
  code: RPC_ERROR_CODE3.INVALID_PARAMS,
12178
12177
  message: `unknown provider: ${requested}`
12179
12178
  });
@@ -12209,18 +12208,18 @@ var createAuthManagementHandlers = ({ state, log: log2 }) => {
12209
12208
  }
12210
12209
  } : {}
12211
12210
  };
12212
- sendResult(id, result);
12211
+ sendResult(id2, result);
12213
12212
  } catch {
12214
- sendError(id, {
12213
+ sendError(id2, {
12215
12214
  code: RPC_ERROR_CODE3.RUNTIME_INTERNAL,
12216
12215
  message: "auth status failed"
12217
12216
  });
12218
12217
  }
12219
12218
  };
12220
- const handleLogin = async (id, params) => {
12221
- if (rejectUnsupported(id)) return;
12219
+ const handleLogin = async (id2, params) => {
12220
+ if (rejectUnsupported(id2)) return;
12222
12221
  if (state.activeRunId) {
12223
- sendError(id, {
12222
+ sendError(id2, {
12224
12223
  code: RPC_ERROR_CODE3.RUNTIME_BUSY,
12225
12224
  message: "runtime busy"
12226
12225
  });
@@ -12229,7 +12228,7 @@ var createAuthManagementHandlers = ({ state, log: log2 }) => {
12229
12228
  const provider = params?.provider;
12230
12229
  const method = params?.method;
12231
12230
  if (typeof provider !== "string" || !PROVIDER_NAME_PATTERN.test(provider)) {
12232
- sendError(id, {
12231
+ sendError(id2, {
12233
12232
  code: RPC_ERROR_CODE3.INVALID_PARAMS,
12234
12233
  message: "invalid provider name"
12235
12234
  });
@@ -12242,21 +12241,21 @@ var createAuthManagementHandlers = ({ state, log: log2 }) => {
12242
12241
  providers = resolved.providers;
12243
12242
  providerConfigs = resolved.config.providers;
12244
12243
  } catch {
12245
- sendError(id, {
12244
+ sendError(id2, {
12246
12245
  code: RPC_ERROR_CODE3.RUNTIME_INTERNAL,
12247
12246
  message: "auth login failed"
12248
12247
  });
12249
12248
  return;
12250
12249
  }
12251
12250
  if (!providers.includes(provider)) {
12252
- sendError(id, {
12251
+ sendError(id2, {
12253
12252
  code: RPC_ERROR_CODE3.INVALID_PARAMS,
12254
12253
  message: `unknown provider: ${provider}`
12255
12254
  });
12256
12255
  return;
12257
12256
  }
12258
12257
  if (!method || !providerAuthMethods(provider, providerConfigs).includes(method)) {
12259
- sendError(id, {
12258
+ sendError(id2, {
12260
12259
  code: RPC_ERROR_CODE3.INVALID_PARAMS,
12261
12260
  message: `unsupported auth method for ${provider}`
12262
12261
  });
@@ -12266,7 +12265,7 @@ var createAuthManagementHandlers = ({ state, log: log2 }) => {
12266
12265
  const raw = params.api_key;
12267
12266
  const apiKey = typeof raw === "string" ? raw.trim() : "";
12268
12267
  if (!apiKey || apiKey.length > MAX_API_KEY_LENGTH || /\s/.test(apiKey)) {
12269
- sendError(id, {
12268
+ sendError(id2, {
12270
12269
  code: RPC_ERROR_CODE3.INVALID_PARAMS,
12271
12270
  message: "api_key must be a non-empty single-line string"
12272
12271
  });
@@ -12284,20 +12283,20 @@ var createAuthManagementHandlers = ({ state, log: log2 }) => {
12284
12283
  return "saved";
12285
12284
  });
12286
12285
  } catch {
12287
- sendError(id, {
12286
+ sendError(id2, {
12288
12287
  code: RPC_ERROR_CODE3.RUNTIME_INTERNAL,
12289
12288
  message: "saving credentials failed"
12290
12289
  });
12291
12290
  return;
12292
12291
  }
12293
12292
  if (saved === "busy") {
12294
- sendError(id, {
12293
+ sendError(id2, {
12295
12294
  code: RPC_ERROR_CODE3.RUNTIME_BUSY,
12296
12295
  message: "runtime busy"
12297
12296
  });
12298
12297
  return;
12299
12298
  }
12300
- sendResult(id, {
12299
+ sendResult(id2, {
12301
12300
  status: "completed",
12302
12301
  provider,
12303
12302
  method: "api_key"
@@ -12306,7 +12305,7 @@ var createAuthManagementHandlers = ({ state, log: log2 }) => {
12306
12305
  return;
12307
12306
  }
12308
12307
  if (pending) {
12309
- sendError(id, {
12308
+ sendError(id2, {
12310
12309
  code: RPC_ERROR_CODE3.RUNTIME_BUSY,
12311
12310
  message: "another login is pending"
12312
12311
  });
@@ -12314,7 +12313,7 @@ var createAuthManagementHandlers = ({ state, log: log2 }) => {
12314
12313
  }
12315
12314
  const typed = params;
12316
12315
  if (typed.callback !== void 0 && typed.callback !== "loopback" && typed.callback !== "paste") {
12317
- sendError(id, {
12316
+ sendError(id2, {
12318
12317
  code: RPC_ERROR_CODE3.INVALID_PARAMS,
12319
12318
  message: "callback must be loopback or paste"
12320
12319
  });
@@ -12337,7 +12336,7 @@ var createAuthManagementHandlers = ({ state, log: log2 }) => {
12337
12336
  return false;
12338
12337
  }
12339
12338
  stop();
12340
- sendError(id, {
12339
+ sendError(id2, {
12341
12340
  code: RPC_ERROR_CODE3.USER_CANCELLED,
12342
12341
  message: "login cancelled"
12343
12342
  });
@@ -12350,7 +12349,7 @@ var createAuthManagementHandlers = ({ state, log: log2 }) => {
12350
12349
  });
12351
12350
  if (cancelledDuringSetup(session.stop)) return;
12352
12351
  login.completeFromInput = session.completeFromInput;
12353
- sendResult(id, {
12352
+ sendResult(id2, {
12354
12353
  status: "pending",
12355
12354
  login_id: login.id,
12356
12355
  provider,
@@ -12368,7 +12367,7 @@ var createAuthManagementHandlers = ({ state, log: log2 }) => {
12368
12367
  const session = await createOpenAiDeviceCodeSession();
12369
12368
  const abort = new AbortController();
12370
12369
  if (cancelledDuringSetup(() => abort.abort())) return;
12371
- sendResult(id, {
12370
+ sendResult(id2, {
12372
12371
  status: "pending",
12373
12372
  login_id: login.id,
12374
12373
  provider,
@@ -12386,17 +12385,17 @@ var createAuthManagementHandlers = ({ state, log: log2 }) => {
12386
12385
  } catch (error) {
12387
12386
  login.settled = true;
12388
12387
  if (pending === login) pending = null;
12389
- sendError(id, {
12388
+ sendError(id2, {
12390
12389
  code: RPC_ERROR_CODE3.RUNTIME_INTERNAL,
12391
12390
  message: `auth login failed: ${failureMessage(error)}`
12392
12391
  });
12393
12392
  }
12394
12393
  };
12395
- const handleLoginComplete = async (id, params) => {
12396
- if (rejectUnsupported(id)) return;
12394
+ const handleLoginComplete = async (id2, params) => {
12395
+ if (rejectUnsupported(id2)) return;
12397
12396
  const login = pending;
12398
12397
  if (!login || login.id !== params?.login_id) {
12399
- sendError(id, {
12398
+ sendError(id2, {
12400
12399
  code: RPC_ERROR_CODE3.INVALID_PARAMS,
12401
12400
  message: "no matching pending login"
12402
12401
  });
@@ -12404,7 +12403,7 @@ var createAuthManagementHandlers = ({ state, log: log2 }) => {
12404
12403
  }
12405
12404
  const input = params?.callback_input;
12406
12405
  if (!login.completeFromInput || typeof input !== "string" || !input.trim() || input.length > MAX_CALLBACK_INPUT_LENGTH) {
12407
- sendError(id, {
12406
+ sendError(id2, {
12408
12407
  code: RPC_ERROR_CODE3.INVALID_PARAMS,
12409
12408
  message: "callback_input is required for a pending OAuth login"
12410
12409
  });
@@ -12414,27 +12413,27 @@ var createAuthManagementHandlers = ({ state, log: log2 }) => {
12414
12413
  try {
12415
12414
  completion = login.completeFromInput(input.trim());
12416
12415
  } catch {
12417
- sendError(id, {
12416
+ sendError(id2, {
12418
12417
  code: RPC_ERROR_CODE3.INVALID_PARAMS,
12419
12418
  message: "invalid OAuth callback input"
12420
12419
  });
12421
12420
  return;
12422
12421
  }
12423
- sendResult(id, { ok: true });
12422
+ sendResult(id2, { ok: true });
12424
12423
  completion.then(
12425
12424
  (tokens) => finishLogin(login, tokens),
12426
12425
  (error) => failLogin(login, error)
12427
12426
  );
12428
12427
  };
12429
- const handleLoginCancel = async (id, params) => {
12430
- if (rejectUnsupported(id)) return;
12428
+ const handleLoginCancel = async (id2, params) => {
12429
+ if (rejectUnsupported(id2)) return;
12431
12430
  const login = pending;
12432
12431
  if (!login || login.id !== params?.login_id) {
12433
- sendResult(id, { cancelled: false });
12432
+ sendResult(id2, { cancelled: false });
12434
12433
  return;
12435
12434
  }
12436
12435
  settle(login);
12437
- sendResult(id, { cancelled: true });
12436
+ sendResult(id2, { cancelled: true });
12438
12437
  notifyLogin(login, "cancelled");
12439
12438
  log2(`auth.login cancelled provider=${login.provider}`);
12440
12439
  };
@@ -12614,19 +12613,19 @@ var createConfigHandlers = ({
12614
12613
  state,
12615
12614
  log: log2
12616
12615
  }) => {
12617
- const rejectUnsupported = (id) => {
12616
+ const rejectUnsupported = (id2) => {
12618
12617
  if (supportsConfigReadWrite(state)) return false;
12619
- sendError(id, {
12618
+ sendError(id2, {
12620
12619
  code: RPC_ERROR_CODE4.INVALID_PARAMS,
12621
12620
  message: "config read/write is not available for this runtime"
12622
12621
  });
12623
12622
  return true;
12624
12623
  };
12625
- const handleConfigGet = async (id, params) => {
12626
- if (rejectUnsupported(id)) return;
12624
+ const handleConfigGet = async (id2, params) => {
12625
+ if (rejectUnsupported(id2)) return;
12627
12626
  const keys = params?.keys;
12628
12627
  if (keys !== void 0 && (!Array.isArray(keys) || keys.length > MAX_KEYS_PER_REQUEST || keys.some((key) => typeof key !== "string" || !findConfigKey(key)))) {
12629
- sendError(id, {
12628
+ sendError(id2, {
12630
12629
  code: RPC_ERROR_CODE4.INVALID_PARAMS,
12631
12630
  message: "keys must list known config keys"
12632
12631
  });
@@ -12639,18 +12638,18 @@ var createConfigHandlers = ({
12639
12638
  entries: specs.map((spec) => buildConfigEntry(spec, layers)),
12640
12639
  ...layers.errors.length ? { errors: layers.errors } : {}
12641
12640
  };
12642
- sendResult(id, result);
12641
+ sendResult(id2, result);
12643
12642
  };
12644
- const handleConfigSet = async (id, params) => {
12645
- if (rejectUnsupported(id)) return;
12643
+ const handleConfigSet = async (id2, params) => {
12644
+ if (rejectUnsupported(id2)) return;
12646
12645
  if (state.activeRunId) {
12647
- sendError(id, {
12646
+ sendError(id2, {
12648
12647
  code: RPC_ERROR_CODE4.RUNTIME_BUSY,
12649
12648
  message: "runtime busy"
12650
12649
  });
12651
12650
  return;
12652
12651
  }
12653
- const invalid = (message) => sendError(id, { code: RPC_ERROR_CODE4.INVALID_PARAMS, message });
12652
+ const invalid = (message) => sendError(id2, { code: RPC_ERROR_CODE4.INVALID_PARAMS, message });
12654
12653
  const scope = params?.scope;
12655
12654
  if (scope !== "global" && scope !== "project") {
12656
12655
  invalid("scope must be global or project");
@@ -12700,14 +12699,14 @@ var createConfigHandlers = ({
12700
12699
  return written;
12701
12700
  });
12702
12701
  } catch {
12703
- sendError(id, {
12702
+ sendError(id2, {
12704
12703
  code: RPC_ERROR_CODE4.RUNTIME_INTERNAL,
12705
12704
  message: `${scope} config write failed`
12706
12705
  });
12707
12706
  return;
12708
12707
  }
12709
12708
  if (changed === "busy") {
12710
- sendError(id, {
12709
+ sendError(id2, {
12711
12710
  code: RPC_ERROR_CODE4.RUNTIME_BUSY,
12712
12711
  message: "runtime busy"
12713
12712
  });
@@ -12721,7 +12720,7 @@ var createConfigHandlers = ({
12721
12720
  entry: buildConfigEntry(spec, layers),
12722
12721
  applies: "next_run"
12723
12722
  };
12724
- sendResult(id, result);
12723
+ sendResult(id2, result);
12725
12724
  log2(
12726
12725
  `config.set ${spec.key} scope=${scope} ${unset ? "unset" : "set"} changed=${changed}`
12727
12726
  );
@@ -12814,7 +12813,7 @@ var createContextHandlers = ({
12814
12813
  return null;
12815
12814
  }
12816
12815
  };
12817
- const handleContextInspect = async (id, params) => {
12816
+ const handleContextInspect = async (id2, params) => {
12818
12817
  const includeAgents = params?.include_agents ?? true;
12819
12818
  const includeSkills = params?.include_skills ?? true;
12820
12819
  try {
@@ -12860,9 +12859,9 @@ var createContextHandlers = ({
12860
12859
  result.skills = snapshot;
12861
12860
  }
12862
12861
  }
12863
- sendResult(id, result);
12862
+ sendResult(id2, result);
12864
12863
  } catch (error) {
12865
- sendError(id, {
12864
+ sendError(id2, {
12866
12865
  code: RPC_ERROR_CODE5.RUNTIME_INTERNAL,
12867
12866
  message: `context.inspect failed: ${String(error)}`
12868
12867
  });
@@ -12889,17 +12888,17 @@ var createContextUsageHandlers = ({
12889
12888
  state,
12890
12889
  log: log2
12891
12890
  }) => {
12892
- const handleContextUsage = async (id) => {
12891
+ const handleContextUsage = async (id2) => {
12893
12892
  try {
12894
12893
  const usage = state.agent ? state.agent.getContextUsage() : emptyUsage(state);
12895
12894
  const result = {
12896
12895
  ...usage,
12897
12896
  ...state.sessionId ? { session_id: state.sessionId } : {}
12898
12897
  };
12899
- sendResult(id, result);
12898
+ sendResult(id2, result);
12900
12899
  } catch (error) {
12901
12900
  log2(`context.usage failed: ${String(error)}`);
12902
- sendError(id, {
12901
+ sendError(id2, {
12903
12902
  code: RPC_ERROR_CODE6.RUNTIME_INTERNAL,
12904
12903
  message: "context usage unavailable"
12905
12904
  });
@@ -13145,14 +13144,14 @@ var createHistoryHandlers = ({
13145
13144
  if (!trimmed) return void 0;
13146
13145
  return path17.resolve(trimmed);
13147
13146
  };
13148
- const handleSessionList = async (id, params) => {
13147
+ const handleSessionList = async (id2, params) => {
13149
13148
  const limit = params?.limit ?? 50;
13150
13149
  const scope = params?.scope ?? "current_workspace";
13151
13150
  let sessions;
13152
13151
  try {
13153
13152
  sessions = await sessionStateStore.list();
13154
13153
  } catch (error) {
13155
- sendError(id, {
13154
+ sendError(id2, {
13156
13155
  code: RPC_ERROR_CODE7.SESSION_LIST_FAILED,
13157
13156
  message: `session list failed: ${String(error)}`
13158
13157
  });
@@ -13170,7 +13169,7 @@ var createHistoryHandlers = ({
13170
13169
  sessions: filtered,
13171
13170
  current_workspace_root: requestedWorkspaceRoot
13172
13171
  };
13173
- sendResult(id, result);
13172
+ sendResult(id2, result);
13174
13173
  };
13175
13174
  const collectRuns = async (sessionId, maxRuns) => {
13176
13175
  if (runIndex) {
@@ -13182,10 +13181,10 @@ var createHistoryHandlers = ({
13182
13181
  }
13183
13182
  return collectSessionRuns(sessionId, maxRuns, log2);
13184
13183
  };
13185
- const handleSessionHistory = async (id, params) => {
13184
+ const handleSessionHistory = async (id2, params) => {
13186
13185
  const sessionId = params?.session_id?.trim();
13187
13186
  if (!sessionId) {
13188
- sendError(id, {
13187
+ sendError(id2, {
13189
13188
  code: RPC_ERROR_CODE7.INVALID_PARAMS,
13190
13189
  message: "session_id is required"
13191
13190
  });
@@ -13198,7 +13197,7 @@ var createHistoryHandlers = ({
13198
13197
  runs: 0,
13199
13198
  events_sent: 0
13200
13199
  };
13201
- sendResult(id, result2);
13200
+ sendResult(id2, result2);
13202
13201
  return;
13203
13202
  }
13204
13203
  const runs = readRunLogs ? await collectRuns(sessionId, maxRuns) : [];
@@ -13213,6 +13212,7 @@ var createHistoryHandlers = ({
13213
13212
  }
13214
13213
  if (!record || typeof record !== "object") continue;
13215
13214
  if (record.type === "run.start") {
13215
+ if (record.source === "goal") continue;
13216
13216
  const input = runStartInputToHiddenMessage(record.input);
13217
13217
  if (input) {
13218
13218
  replayEvents.push({
@@ -13258,7 +13258,7 @@ var createHistoryHandlers = ({
13258
13258
  ...truncated ? { truncated: true } : {},
13259
13259
  ...resumeDiff ? { resume_diff: resumeDiff } : {}
13260
13260
  };
13261
- sendResult(id, result);
13261
+ sendResult(id2, result);
13262
13262
  };
13263
13263
  return { handleSessionList, handleSessionHistory };
13264
13264
  };
@@ -13386,23 +13386,23 @@ function createImageHandlers(state) {
13386
13386
  const codex = chat?.auth.method === "oauth";
13387
13387
  model = await pick(
13388
13388
  codex ? "Codex OAuth image model (current login; account-specific limits)" : "Image model (API billed; availability is account-specific)",
13389
- (codex ? OPENAI_CODEX_IMAGE_MODELS2 : OPENAI_IMAGE_MODELS2).map((id) => ({
13390
- id,
13391
- label: id,
13389
+ (codex ? OPENAI_CODEX_IMAGE_MODELS2 : OPENAI_IMAGE_MODELS2).map((id2) => ({
13390
+ id: id2,
13391
+ label: id2,
13392
13392
  ...codex ? {
13393
- detail: id === "gpt-image-2" ? "Inspected Codex tool default" : "Explicit request; support/effective model depends on the Codex backend"
13393
+ detail: id2 === "gpt-image-2" ? "Inspected Codex tool default" : "Explicit request; support/effective model depends on the Codex backend"
13394
13394
  } : {}
13395
13395
  }))
13396
13396
  );
13397
13397
  } else if (provider === "google") {
13398
13398
  model = await pick(
13399
13399
  "Gemini image model",
13400
- GOOGLE_IMAGE_MODELS.map((id) => ({ id, label: id }))
13400
+ GOOGLE_IMAGE_MODELS.map((id2) => ({ id: id2, label: id2 }))
13401
13401
  );
13402
13402
  if (!model) return null;
13403
13403
  const image_size = await pick(
13404
13404
  "Image size",
13405
- (model === "gemini-3.1-flash-lite-image" ? ["1K"] : ["1K", "2K", "4K"]).map((id) => ({ id, label: id }))
13405
+ (model === "gemini-3.1-flash-lite-image" ? ["1K"] : ["1K", "2K", "4K"]).map((id2) => ({ id: id2, label: id2 }))
13406
13406
  );
13407
13407
  if (!image_size) return null;
13408
13408
  const aspect_ratio = await pick(
@@ -13419,7 +13419,7 @@ function createImageHandlers(state) {
13419
13419
  "16:9",
13420
13420
  "21:9",
13421
13421
  ...model === "gemini-nano-banana-2.1" ? ["1:4", "4:1", "1:8", "8:1"] : []
13422
- ].map((id) => ({ id, label: id }))
13422
+ ].map((id2) => ({ id: id2, label: id2 }))
13423
13423
  );
13424
13424
  if (!aspect_ratio) return null;
13425
13425
  const format = await pick("Image output format", [
@@ -13465,7 +13465,7 @@ function createImageHandlers(state) {
13465
13465
  }
13466
13466
  );
13467
13467
  };
13468
- const handle = async (id, operation, params) => {
13468
+ const handle = async (id2, operation, params) => {
13469
13469
  let ownsConfiguration = false;
13470
13470
  try {
13471
13471
  const root = workspace();
@@ -13479,14 +13479,14 @@ function createImageHandlers(state) {
13479
13479
  root,
13480
13480
  () => state.sessionId
13481
13481
  ).read(parsed2.data.artifact_id);
13482
- sendResult(id, {
13482
+ sendResult(id2, {
13483
13483
  metadata,
13484
13484
  data_url: `data:${metadata.media_type};base64,${bytes.toString("base64")}`
13485
13485
  });
13486
13486
  return;
13487
13487
  }
13488
13488
  if (operation === "get") {
13489
- sendResult(id, await status(await resolveImageGenerationConfig(root)));
13489
+ sendResult(id2, await status(await resolveImageGenerationConfig(root)));
13490
13490
  return;
13491
13491
  }
13492
13492
  if (state.activeRunId || configuring)
@@ -13541,7 +13541,7 @@ function createImageHandlers(state) {
13541
13541
  config = await choose();
13542
13542
  }
13543
13543
  if (!config) {
13544
- sendResult(id, { message: "Image settings unchanged." });
13544
+ sendResult(id2, { message: "Image settings unchanged." });
13545
13545
  return;
13546
13546
  }
13547
13547
  const next = await status(config);
@@ -13558,7 +13558,7 @@ This saves image settings only; generation requests use the tool permission poli
13558
13558
  cancel_label: "Cancel"
13559
13559
  });
13560
13560
  if (!confirm?.ok) {
13561
- sendResult(id, { message: "Image settings unchanged." });
13561
+ sendResult(id2, { message: "Image settings unchanged." });
13562
13562
  return;
13563
13563
  }
13564
13564
  }
@@ -13570,9 +13570,9 @@ This saves image settings only; generation requests use the tool permission poli
13570
13570
  state.agent = null;
13571
13571
  state.tools = null;
13572
13572
  state.toolDefinitions = null;
13573
- sendResult(id, next);
13573
+ sendResult(id2, next);
13574
13574
  } catch (error) {
13575
- sendError(id, {
13575
+ sendError(id2, {
13576
13576
  code: RPC_ERROR_CODE8.INVALID_PARAMS,
13577
13577
  message: error instanceof ImageGenerationError ? error.message : "Image operation failed; check settings, artifact and runtime storage. No credentials were changed."
13578
13578
  });
@@ -13763,13 +13763,13 @@ var parseOpenRouterModel = (value) => {
13763
13763
  return null;
13764
13764
  }
13765
13765
  const entry = value;
13766
- const id = typeof entry.id === "string" ? entry.id.trim() : "";
13767
- if (!id) {
13766
+ const id2 = typeof entry.id === "string" ? entry.id.trim() : "";
13767
+ if (!id2) {
13768
13768
  return null;
13769
13769
  }
13770
13770
  const topProvider = entry.top_provider && typeof entry.top_provider === "object" ? entry.top_provider : null;
13771
13771
  return {
13772
- id,
13772
+ id: id2,
13773
13773
  created: typeof entry.created === "number" && Number.isFinite(entry.created) ? entry.created : void 0,
13774
13774
  context_length: parsePositiveNumber(entry.context_length),
13775
13775
  top_provider: topProvider ? {
@@ -13938,12 +13938,13 @@ var createModelHandlers = ({
13938
13938
  model: name2,
13939
13939
  requested: fast
13940
13940
  });
13941
- if (fast === "ultrafast") {
13942
- const auth = state.effectiveEnvironment.auth.model === "host" ? await state.effectiveEnvironment.adapters.credentialProvider?.resolveProviderAuth(
13943
- provider
13944
- ) : (await new AuthStore().load()).providers[provider];
13945
- const method = auth?.method ?? (state.effectiveEnvironment.auth.model !== "host" && readEnvValue("OPENAI_API_KEY") ? "api_key" : "missing");
13946
- assertUltrafastAuth(fast, method);
13941
+ if (fast !== "ultrafast") return effectiveFast;
13942
+ const { auth: authPolicy, adapters } = state.effectiveEnvironment;
13943
+ const credentials = authPolicy.model === "host" ? await adapters.credentialProvider?.resolveProviderAuth(provider) : (await new AuthStore().load()).providers[provider] ?? readEnvValue("OPENAI_API_KEY");
13944
+ if (!credentials) {
13945
+ throw new Error(
13946
+ "Ultrafast requires OpenAI API-key or ChatGPT sign-in credentials."
13947
+ );
13947
13948
  }
13948
13949
  return effectiveFast;
13949
13950
  };
@@ -13962,7 +13963,7 @@ var createModelHandlers = ({
13962
13963
  meta: nextMeta
13963
13964
  });
13964
13965
  };
13965
- const handleModelList = async (id, params) => {
13966
+ const handleModelList = async (id2, params) => {
13966
13967
  const requestedProvider = params?.provider;
13967
13968
  const includeDetails = params?.include_details ?? false;
13968
13969
  let providers;
@@ -13989,7 +13990,7 @@ var createModelHandlers = ({
13989
13990
  });
13990
13991
  }
13991
13992
  } catch (error) {
13992
- sendError(id, {
13993
+ sendError(id2, {
13993
13994
  code: RPC_ERROR_CODE9.RUNTIME_INTERNAL,
13994
13995
  message: String(error)
13995
13996
  });
@@ -13997,7 +13998,7 @@ var createModelHandlers = ({
13997
13998
  }
13998
13999
  const provider = requestedProvider ?? configuredProvider ?? "openai";
13999
14000
  if (!isSupportedProvider(provider, providers)) {
14000
- sendError(id, {
14001
+ sendError(id2, {
14001
14002
  code: RPC_ERROR_CODE9.INVALID_PARAMS,
14002
14003
  message: `unsupported provider: ${provider}`
14003
14004
  });
@@ -14016,7 +14017,7 @@ var createModelHandlers = ({
14016
14017
  models = result2.models;
14017
14018
  details = result2.details;
14018
14019
  } catch (error) {
14019
- sendError(id, {
14020
+ sendError(id2, {
14020
14021
  code: RPC_ERROR_CODE9.RUNTIME_INTERNAL,
14021
14022
  message: String(error)
14022
14023
  });
@@ -14043,11 +14044,11 @@ var createModelHandlers = ({
14043
14044
  ...configuredFast !== void 0 ? { fast: configuredFast } : {},
14044
14045
  ...details ? { details } : {}
14045
14046
  };
14046
- sendResult(id, result);
14047
+ sendResult(id2, result);
14047
14048
  };
14048
- const handleModelSet = async (id, params) => {
14049
+ const handleModelSet = async (id2, params) => {
14049
14050
  if (state.activeRunId) {
14050
- sendError(id, {
14051
+ sendError(id2, {
14051
14052
  code: RPC_ERROR_CODE9.RUNTIME_BUSY,
14052
14053
  message: "runtime busy"
14053
14054
  });
@@ -14055,7 +14056,7 @@ var createModelHandlers = ({
14055
14056
  }
14056
14057
  const scope = params?.scope ?? "config";
14057
14058
  if (scope !== "config" && scope !== "session") {
14058
- sendError(id, {
14059
+ sendError(id2, {
14059
14060
  code: RPC_ERROR_CODE9.INVALID_PARAMS,
14060
14061
  message: `unsupported model scope: ${scope}`
14061
14062
  });
@@ -14064,7 +14065,7 @@ var createModelHandlers = ({
14064
14065
  const workingDir = state.lastUiContext?.cwd ?? state.runtimeWorkingDir ?? process.cwd();
14065
14066
  if (params?.reset) {
14066
14067
  if (scope !== "session") {
14067
- sendError(id, {
14068
+ sendError(id2, {
14068
14069
  code: RPC_ERROR_CODE9.INVALID_PARAMS,
14069
14070
  message: "model reset is only supported for session scope"
14070
14071
  });
@@ -14075,7 +14076,7 @@ var createModelHandlers = ({
14075
14076
  const provider2 = config.provider ?? "openai";
14076
14077
  const name3 = config.name;
14077
14078
  if (!name3) {
14078
- sendError(id, {
14079
+ sendError(id2, {
14079
14080
  code: RPC_ERROR_CODE9.RUNTIME_INTERNAL,
14080
14081
  message: "configured model name is missing"
14081
14082
  });
@@ -14091,7 +14092,7 @@ var createModelHandlers = ({
14091
14092
  config.fast
14092
14093
  );
14093
14094
  } catch (error) {
14094
- sendError(id, {
14095
+ sendError(id2, {
14095
14096
  code: RPC_ERROR_CODE9.INVALID_PARAMS,
14096
14097
  message: String(error)
14097
14098
  });
@@ -14110,10 +14111,10 @@ var createModelHandlers = ({
14110
14111
  ...effectiveReasoning ? { reasoning: effectiveReasoning } : {},
14111
14112
  ...config.fast !== void 0 ? { fast: effectiveFast } : {}
14112
14113
  };
14113
- sendResult(id, result);
14114
+ sendResult(id2, result);
14114
14115
  log2(`model.set reset session override -> ${provider2}/${name3}`);
14115
14116
  } catch (error) {
14116
- sendError(id, {
14117
+ sendError(id2, {
14117
14118
  code: RPC_ERROR_CODE9.RUNTIME_INTERNAL,
14118
14119
  message: String(error)
14119
14120
  });
@@ -14123,7 +14124,7 @@ var createModelHandlers = ({
14123
14124
  const provider = params?.provider ?? "openai";
14124
14125
  let name2 = params?.name?.trim();
14125
14126
  if (!name2) {
14126
- sendError(id, {
14127
+ sendError(id2, {
14127
14128
  code: RPC_ERROR_CODE9.INVALID_PARAMS,
14128
14129
  message: "model name is required"
14129
14130
  });
@@ -14134,7 +14135,7 @@ var createModelHandlers = ({
14134
14135
  try {
14135
14136
  reasoning = resolveReasoningEffort(params.reasoning);
14136
14137
  } catch (error) {
14137
- sendError(id, {
14138
+ sendError(id2, {
14138
14139
  code: RPC_ERROR_CODE9.INVALID_PARAMS,
14139
14140
  message: String(error)
14140
14141
  });
@@ -14144,7 +14145,7 @@ var createModelHandlers = ({
14144
14145
  const configured = await resolveEnvironmentModelConfig(state, workingDir);
14145
14146
  const endpoint = getResponsesProvider(configured, provider);
14146
14147
  if (!isSupportedProvider(provider, configured.providers)) {
14147
- sendError(id, {
14148
+ sendError(id2, {
14148
14149
  code: RPC_ERROR_CODE9.INVALID_PARAMS,
14149
14150
  message: `unsupported provider: ${provider}`
14150
14151
  });
@@ -14157,7 +14158,7 @@ var createModelHandlers = ({
14157
14158
  provider
14158
14159
  );
14159
14160
  if (!spec) {
14160
- sendError(id, {
14161
+ sendError(id2, {
14161
14162
  code: RPC_ERROR_CODE9.INVALID_PARAMS,
14162
14163
  message: `unknown model: ${name2}`
14163
14164
  });
@@ -14190,16 +14191,16 @@ var createModelHandlers = ({
14190
14191
  }
14191
14192
  await validateFastSelection(provider, name2, candidate.fast);
14192
14193
  } catch (error) {
14193
- sendError(id, {
14194
+ sendError(id2, {
14194
14195
  code: RPC_ERROR_CODE9.INVALID_PARAMS,
14195
14196
  message: String(error)
14196
14197
  });
14197
14198
  return;
14198
14199
  }
14199
14200
  try {
14200
- let target = null;
14201
+ let target2 = null;
14201
14202
  if (scope === "config") {
14202
- target = await updateEnvironmentModel(state, workingDir, {
14203
+ target2 = await updateEnvironmentModel(state, workingDir, {
14203
14204
  provider,
14204
14205
  name: name2,
14205
14206
  ...reasoning ? { reasoning } : {},
@@ -14239,13 +14240,13 @@ var createModelHandlers = ({
14239
14240
  ...effectiveReasoning ? { reasoning: effectiveReasoning } : {},
14240
14241
  ...updatedConfig.fast !== void 0 ? { fast: effectiveFast } : {}
14241
14242
  };
14242
- sendResult(id, result);
14243
- const persistence = scope === "config" && target ? ` scope=${target.scope} path=${target.path}` : " scope=session";
14243
+ sendResult(id2, result);
14244
+ const persistence = scope === "config" && target2 ? ` scope=${target2.scope} path=${target2.path}` : " scope=session";
14244
14245
  log2(
14245
14246
  `model.set ${provider}/${name2}${effectiveReasoning ? ` reasoning=${effectiveReasoning}` : ""}${persistence}`
14246
14247
  );
14247
14248
  } catch (error) {
14248
- sendError(id, {
14249
+ sendError(id2, {
14249
14250
  code: RPC_ERROR_CODE9.RUNTIME_INTERNAL,
14250
14251
  message: String(error)
14251
14252
  });
@@ -14302,18 +14303,18 @@ var createPermissionsHandlers = ({
14302
14303
  state,
14303
14304
  log: log2
14304
14305
  }) => {
14305
- const rejectUnsupported = (id) => {
14306
+ const rejectUnsupported = (id2) => {
14306
14307
  if (supportsConfigReadWrite(state)) return false;
14307
- sendError(id, {
14308
+ sendError(id2, {
14308
14309
  code: RPC_ERROR_CODE10.INVALID_PARAMS,
14309
14310
  message: "permission rules are not available for this runtime"
14310
14311
  });
14311
14312
  return true;
14312
14313
  };
14313
- const handlePermissionsList = async (id, params) => {
14314
- if (rejectUnsupported(id)) return;
14314
+ const handlePermissionsList = async (id2, params) => {
14315
+ if (rejectUnsupported(id2)) return;
14315
14316
  if (params?.include_system !== void 0 && typeof params.include_system !== "boolean") {
14316
- sendError(id, {
14317
+ sendError(id2, {
14317
14318
  code: RPC_ERROR_CODE10.INVALID_PARAMS,
14318
14319
  message: "include_system must be a boolean"
14319
14320
  });
@@ -14377,18 +14378,18 @@ var createPermissionsHandlers = ({
14377
14378
  rules,
14378
14379
  ...errors.length ? { errors } : {}
14379
14380
  };
14380
- sendResult(id, result);
14381
+ sendResult(id2, result);
14381
14382
  };
14382
- const handlePermissionsRemove = async (id, params) => {
14383
- if (rejectUnsupported(id)) return;
14383
+ const handlePermissionsRemove = async (id2, params) => {
14384
+ if (rejectUnsupported(id2)) return;
14384
14385
  if (state.activeRunId) {
14385
- sendError(id, {
14386
+ sendError(id2, {
14386
14387
  code: RPC_ERROR_CODE10.RUNTIME_BUSY,
14387
14388
  message: "runtime busy"
14388
14389
  });
14389
14390
  return;
14390
14391
  }
14391
- const invalid = (message) => sendError(id, { code: RPC_ERROR_CODE10.INVALID_PARAMS, message });
14392
+ const invalid = (message) => sendError(id2, { code: RPC_ERROR_CODE10.INVALID_PARAMS, message });
14392
14393
  const scope = params?.scope;
14393
14394
  const kind = params?.kind;
14394
14395
  if (scope !== "global" && scope !== "project") {
@@ -14419,21 +14420,21 @@ var createPermissionsHandlers = ({
14419
14420
  return count2;
14420
14421
  });
14421
14422
  } catch {
14422
- sendError(id, {
14423
+ sendError(id2, {
14423
14424
  code: RPC_ERROR_CODE10.RUNTIME_INTERNAL,
14424
14425
  message: `${scope} config write failed`
14425
14426
  });
14426
14427
  return;
14427
14428
  }
14428
14429
  if (removed === "busy") {
14429
- sendError(id, {
14430
+ sendError(id2, {
14430
14431
  code: RPC_ERROR_CODE10.RUNTIME_BUSY,
14431
14432
  message: "runtime busy"
14432
14433
  });
14433
14434
  return;
14434
14435
  }
14435
14436
  const result = { scope, kind, path: path23, removed };
14436
- sendResult(id, result);
14437
+ sendResult(id2, result);
14437
14438
  log2(`permissions.remove scope=${scope} kind=${kind} removed=${removed}`);
14438
14439
  };
14439
14440
  return { handlePermissionsList, handlePermissionsRemove };
@@ -14813,28 +14814,28 @@ var buildResumeDiff = async (meta, state, options = {}) => {
14813
14814
 
14814
14815
  // src/rpc/run.ts
14815
14816
  import {
14816
- RPC_ERROR_CODE as RPC_ERROR_CODE11
14817
+ RPC_ERROR_CODE as RPC_ERROR_CODE12
14817
14818
  } from "@codelia/protocol";
14818
14819
 
14819
14820
  // src/rpc/client-tool-requests.ts
14820
14821
  var requestClientToolCall = async (state, params, timeoutMs) => {
14821
- const id = state.nextUiRequestId();
14822
+ const id2 = state.nextUiRequestId();
14822
14823
  const request = {
14823
14824
  jsonrpc: "2.0",
14824
- id,
14825
+ id: id2,
14825
14826
  method: "client.tool.call",
14826
14827
  params
14827
14828
  };
14828
14829
  send(request);
14829
14830
  return await state.waitForUiResponse(
14830
- id,
14831
+ id2,
14831
14832
  timeoutMs,
14832
14833
  () => {
14833
14834
  const notification = {
14834
14835
  jsonrpc: "2.0",
14835
14836
  method: "client.tool.cancel",
14836
14837
  params: {
14837
- request_id: id,
14838
+ request_id: id2,
14838
14839
  run_id: params.run_id,
14839
14840
  name: params.name,
14840
14841
  reason: "timeout"
@@ -14944,6 +14945,552 @@ var createClientToolAdapters = ({
14944
14945
  });
14945
14946
  };
14946
14947
 
14948
+ // src/rpc/goals.ts
14949
+ import {
14950
+ defineTool as defineTool22
14951
+ } from "@codelia/core";
14952
+ import { RPC_ERROR_CODE as RPC_ERROR_CODE11 } from "@codelia/protocol";
14953
+ import {
14954
+ getProcessIdentity as getProcessIdentity2
14955
+ } from "@codelia/storage";
14956
+ import { z as z30 } from "zod";
14957
+ var id = z30.string().min(1).max(200);
14958
+ var revision = z30.number().int().positive();
14959
+ var target = z30.object({ session_id: id, goal_id: id, revision });
14960
+ var budget = z30.number().int().positive().nullable();
14961
+ var schemas = {
14962
+ "goal.get": z30.object({
14963
+ session_id: id.optional(),
14964
+ continuation_id: id.optional()
14965
+ }),
14966
+ "goal.set": target.partial().extend({
14967
+ objective: z30.string().trim().min(1).max(8e3).optional(),
14968
+ token_budget: budget.optional()
14969
+ }),
14970
+ "goal.pause": z30.object({
14971
+ session_id: id,
14972
+ goal_id: id,
14973
+ activation_id: id,
14974
+ run_id: id.optional(),
14975
+ continuation_id: id.optional()
14976
+ }),
14977
+ "goal.resume": target,
14978
+ "goal.clear": target
14979
+ };
14980
+ var readySchema = target.extend({
14981
+ continuation_id: id,
14982
+ after_run_id: id.optional()
14983
+ });
14984
+ var GoalConflict = class extends Error {
14985
+ constructor(message, reason = "conflict") {
14986
+ super(message);
14987
+ this.reason = reason;
14988
+ }
14989
+ reason;
14990
+ };
14991
+ var stamp = () => (/* @__PURE__ */ new Date()).toISOString();
14992
+ var transition = (goal, status, reason) => {
14993
+ if (goal.status !== status || goal.stop_reason !== reason)
14994
+ goal.stop_detail = void 0;
14995
+ goal.status = status;
14996
+ goal.stop_reason = reason;
14997
+ goal.revision += 1;
14998
+ goal.updated_at = stamp();
14999
+ };
15000
+ function stopForBudget(goal) {
15001
+ if (goal.token_budget === null) return false;
15002
+ if (goal.tokens_used >= goal.token_budget) {
15003
+ transition(goal, "budget_limited");
15004
+ return true;
15005
+ }
15006
+ if (!goal.usage_known) {
15007
+ transition(goal, "usage_limited");
15008
+ return true;
15009
+ }
15010
+ return false;
15011
+ }
15012
+ var readTarget = (entry, expected) => {
15013
+ if (!entry || entry.goal.goal_id !== expected.goal_id || entry.goal.revision !== expected.revision)
15014
+ throw new GoalConflict("Goal changed. Use /goal to refresh.");
15015
+ return entry;
15016
+ };
15017
+ var GoalController = class {
15018
+ constructor(state, store, sessions, workspaceRoot) {
15019
+ this.state = state;
15020
+ this.store = store;
15021
+ this.sessions = sessions;
15022
+ this.workspaceRoot = workspaceRoot;
15023
+ }
15024
+ state;
15025
+ store;
15026
+ sessions;
15027
+ workspaceRoot;
15028
+ activation = null;
15029
+ offer = null;
15030
+ activeRun;
15031
+ identity;
15032
+ get enabled() {
15033
+ return this.state.uiCapabilities?.supports_goals === true;
15034
+ }
15035
+ disarm() {
15036
+ this.activation = null;
15037
+ this.offer = null;
15038
+ }
15039
+ owns(goal) {
15040
+ return this.activation?.sessionId === goal.session_id && this.activation.goalId === goal.goal_id && this.activation.id === goal.activation_id;
15041
+ }
15042
+ arm(goal) {
15043
+ this.activation = {
15044
+ sessionId: goal.session_id,
15045
+ goalId: goal.goal_id,
15046
+ id: goal.activation_id
15047
+ };
15048
+ this.offer = null;
15049
+ }
15050
+ snapshot(sessionId, goal, acceptedRunId) {
15051
+ return {
15052
+ session_id: sessionId,
15053
+ goal,
15054
+ can_continue: Boolean(goal?.status === "active" && this.owns(goal)),
15055
+ ...acceptedRunId ? {
15056
+ accepted_run_id: acceptedRunId,
15057
+ ...this.state.activeRunId === acceptedRunId ? { active_run_id: acceptedRunId } : {}
15058
+ } : {}
15059
+ };
15060
+ }
15061
+ publish(goal) {
15062
+ if (this.enabled && this.state.sessionId === goal.session_id)
15063
+ send({
15064
+ jsonrpc: "2.0",
15065
+ method: "goal.updated",
15066
+ params: this.snapshot(goal.session_id, goal)
15067
+ });
15068
+ }
15069
+ ready(goal, afterRunId) {
15070
+ if (!this.enabled || this.state.activeRunId || this.state.sessionId !== goal.session_id || goal.status !== "active" || !this.owns(goal) || this.offer)
15071
+ return;
15072
+ this.offer = {
15073
+ session_id: goal.session_id,
15074
+ goal_id: goal.goal_id,
15075
+ revision: goal.revision,
15076
+ continuation_id: crypto.randomUUID(),
15077
+ ...afterRunId ? { after_run_id: afterRunId } : {}
15078
+ };
15079
+ send({ jsonrpc: "2.0", method: "goal.ready", params: this.offer });
15080
+ }
15081
+ bound(requested) {
15082
+ if (requested !== void 0 && requested !== this.state.sessionId)
15083
+ throw new GoalConflict("Goal request belongs to a different session.");
15084
+ return this.state.sessionId;
15085
+ }
15086
+ requireIdle() {
15087
+ if (this.state.activeRunId)
15088
+ throw new GoalConflict("Wait for the active run to finish.", "busy");
15089
+ }
15090
+ async recoverable(claim) {
15091
+ try {
15092
+ process.kill(claim.owner_pid, 0);
15093
+ } catch (error) {
15094
+ return error.code === "ESRCH";
15095
+ }
15096
+ if (!claim.owner_identity) return false;
15097
+ const current = await getProcessIdentity2(claim.owner_pid, {
15098
+ canonicalEnvironment: true
15099
+ });
15100
+ return current !== null && current !== claim.owner_identity;
15101
+ }
15102
+ /** Pause intent is latched before joining the admission queue. */
15103
+ handle(requestId, method, raw, serialize, interrupt, onError) {
15104
+ if (!this.enabled) {
15105
+ sendError(requestId, {
15106
+ code: RPC_ERROR_CODE11.INVALID_PARAMS,
15107
+ message: "Goals are unavailable on this connection."
15108
+ });
15109
+ return Promise.resolve();
15110
+ }
15111
+ const pause = method === "goal.pause" ? schemas[method].safeParse(raw) : void 0;
15112
+ const revoked = pause?.success && this.activation?.sessionId === pause.data.session_id && this.activation.goalId === pause.data.goal_id && this.activation.id === pause.data.activation_id;
15113
+ if (revoked) this.disarm();
15114
+ if (pause?.success && this.state.sessionId === pause.data.session_id) {
15115
+ const { goal_id, activation_id, run_id, continuation_id } = pause.data;
15116
+ const run = this.activeRun;
15117
+ if (run?.goal.goal_id === goal_id && run.goal.activation_id === activation_id && (run_id === run.runId || continuation_id !== void 0 && continuation_id === run.continuationId))
15118
+ interrupt(run.runId);
15119
+ }
15120
+ return serialize(async () => {
15121
+ let goal;
15122
+ let sessionId;
15123
+ let cleared = false;
15124
+ switch (method) {
15125
+ case "goal.get": {
15126
+ const params = schemas[method].parse(raw ?? {});
15127
+ sessionId = this.bound(params.session_id);
15128
+ const result = sessionId ? await this.store.read(sessionId, params.continuation_id) : null;
15129
+ sendResult(
15130
+ requestId,
15131
+ this.snapshot(
15132
+ sessionId,
15133
+ result?.entry?.goal ?? null,
15134
+ result?.acceptedRunId
15135
+ )
15136
+ );
15137
+ return;
15138
+ }
15139
+ case "goal.set": {
15140
+ const params = schemas[method].parse(raw);
15141
+ this.requireIdle();
15142
+ sessionId = this.bound(params.session_id);
15143
+ const fresh = sessionId === null;
15144
+ if (fresh && !params.objective)
15145
+ throw new GoalConflict("Set a goal first.");
15146
+ const key = sessionId ?? this.state.nextSessionId();
15147
+ if (fresh) {
15148
+ const root = this.workspaceRoot();
15149
+ const meta = mergeSessionModelOverrideIntoMeta(
15150
+ root ? { codelia_workspace_root: root } : void 0,
15151
+ this.state.sessionModelOverride
15152
+ );
15153
+ await this.sessions.save({
15154
+ schema_version: 1,
15155
+ session_id: key,
15156
+ updated_at: stamp(),
15157
+ messages: [],
15158
+ ...meta ? { meta } : {}
15159
+ });
15160
+ }
15161
+ let created = false;
15162
+ goal = await this.store.update(key, (tx) => {
15163
+ if (!tx.entry) {
15164
+ if (!params.objective || params.goal_id !== void 0 || params.revision !== void 0)
15165
+ throw new GoalConflict("Set a goal first.");
15166
+ const now = stamp();
15167
+ created = true;
15168
+ tx.entry = {
15169
+ goal: {
15170
+ session_id: key,
15171
+ goal_id: crypto.randomUUID(),
15172
+ revision: 1,
15173
+ objective: params.objective,
15174
+ status: "active",
15175
+ token_budget: params.token_budget ?? null,
15176
+ tokens_used: 0,
15177
+ usage_known: true,
15178
+ activation_id: crypto.randomUUID(),
15179
+ automatic_runs: 0,
15180
+ created_at: now,
15181
+ updated_at: now
15182
+ }
15183
+ };
15184
+ return tx.entry.goal;
15185
+ }
15186
+ const expected = target.parse(params);
15187
+ const entry = readTarget(tx.entry, expected);
15188
+ if (entry.claim)
15189
+ throw new GoalConflict("A goal run is still reserved.", "busy");
15190
+ if (entry.goal.status === "complete")
15191
+ throw new GoalConflict("Clear the completed goal first.");
15192
+ if (params.objective !== void 0) {
15193
+ entry.goal.objective = params.objective;
15194
+ entry.blocker = void 0;
15195
+ }
15196
+ if (params.token_budget !== void 0)
15197
+ entry.goal.token_budget = params.token_budget;
15198
+ if (entry.goal.status !== "active" || !stopForBudget(entry.goal))
15199
+ transition(entry.goal, entry.goal.status, entry.goal.stop_reason);
15200
+ return entry.goal;
15201
+ });
15202
+ if (fresh) {
15203
+ this.state.sessionId = key;
15204
+ this.state.attachments?.bindDraft(key);
15205
+ }
15206
+ sessionId = key;
15207
+ if (created) this.arm(goal);
15208
+ else this.offer = null;
15209
+ break;
15210
+ }
15211
+ case "goal.pause": {
15212
+ const params = schemas[method].parse(raw);
15213
+ this.bound(params.session_id);
15214
+ sessionId = params.session_id;
15215
+ if (!revoked)
15216
+ throw new GoalConflict("Goal is not active on this connection.");
15217
+ goal = await this.store.update(sessionId, ({ entry }) => {
15218
+ if (!entry || entry.goal.goal_id !== params.goal_id || entry.goal.activation_id !== params.activation_id)
15219
+ throw new GoalConflict("Goal changed. Use /goal to refresh.");
15220
+ if (entry.goal.status === "active")
15221
+ transition(entry.goal, "paused", "user");
15222
+ return entry.goal;
15223
+ });
15224
+ break;
15225
+ }
15226
+ case "goal.resume": {
15227
+ const params = schemas[method].parse(raw);
15228
+ this.bound(params.session_id);
15229
+ this.requireIdle();
15230
+ sessionId = params.session_id;
15231
+ const previous = readTarget(
15232
+ (await this.store.read(sessionId)).entry,
15233
+ params
15234
+ );
15235
+ if (previous.goal.status === "complete")
15236
+ throw new GoalConflict("Goal is complete.");
15237
+ const orphan = previous.claim;
15238
+ if (orphan && !await this.recoverable(orphan))
15239
+ throw new GoalConflict(
15240
+ "A goal run is still reserved by a live or unverified runtime.",
15241
+ "busy"
15242
+ );
15243
+ goal = await this.store.update(sessionId, (tx) => {
15244
+ const entry = readTarget(tx.entry, params);
15245
+ if (entry.claim?.run_id !== orphan?.run_id)
15246
+ throw new GoalConflict("Goal run reservation changed.", "busy");
15247
+ if (orphan?.pending_seq !== void 0)
15248
+ entry.goal.usage_known = false;
15249
+ entry.claim = void 0;
15250
+ if (stopForBudget(entry.goal)) return entry.goal;
15251
+ entry.goal.activation_id = crypto.randomUUID();
15252
+ entry.goal.automatic_runs = 0;
15253
+ entry.blocker = void 0;
15254
+ transition(entry.goal, "active");
15255
+ return entry.goal;
15256
+ });
15257
+ if (goal.status === "active") this.arm(goal);
15258
+ else this.disarm();
15259
+ break;
15260
+ }
15261
+ case "goal.clear": {
15262
+ const params = schemas[method].parse(raw);
15263
+ this.bound(params.session_id);
15264
+ this.requireIdle();
15265
+ sessionId = params.session_id;
15266
+ await this.store.update(sessionId, (tx) => {
15267
+ if (readTarget(tx.entry, params).claim)
15268
+ throw new GoalConflict("A goal run is still reserved.", "busy");
15269
+ tx.entry = null;
15270
+ });
15271
+ this.disarm();
15272
+ goal = null;
15273
+ cleared = true;
15274
+ }
15275
+ }
15276
+ const snapshot = this.snapshot(sessionId, goal);
15277
+ sendResult(requestId, snapshot);
15278
+ if (cleared)
15279
+ send({ jsonrpc: "2.0", method: "goal.cleared", params: snapshot });
15280
+ if (goal) {
15281
+ this.publish(goal);
15282
+ if (method === "goal.set" || method === "goal.resume") this.ready(goal);
15283
+ }
15284
+ }).catch((error) => {
15285
+ if (!(error instanceof GoalConflict) && !(error instanceof z30.ZodError)) {
15286
+ if (method !== "goal.get") this.disarm();
15287
+ onError(error);
15288
+ }
15289
+ this.reject(requestId, error);
15290
+ });
15291
+ }
15292
+ reject(requestId, error) {
15293
+ const conflict = error instanceof GoalConflict ? error : null;
15294
+ sendError(requestId, {
15295
+ code: conflict?.reason === "busy" ? RPC_ERROR_CODE11.RUNTIME_BUSY : conflict || error instanceof z30.ZodError ? RPC_ERROR_CODE11.INVALID_PARAMS : RPC_ERROR_CODE11.RUNTIME_INTERNAL,
15296
+ message: conflict?.message ?? (error instanceof z30.ZodError ? "Invalid goal parameters." : "Goal operation failed.")
15297
+ });
15298
+ }
15299
+ validateOffer(raw) {
15300
+ if (!this.enabled)
15301
+ throw new GoalConflict("Goals are unavailable on this connection.");
15302
+ const offer = readySchema.parse(raw);
15303
+ this.bound(offer.session_id);
15304
+ if (!this.offer || this.offer.continuation_id !== offer.continuation_id || this.offer.goal_id !== offer.goal_id || this.offer.revision !== offer.revision || this.offer.after_run_id !== offer.after_run_id)
15305
+ throw new GoalConflict("Continuation is stale or already used.");
15306
+ return offer;
15307
+ }
15308
+ canStart(run) {
15309
+ return this.owns(run.goal);
15310
+ }
15311
+ stopAfterStorageFailure(run) {
15312
+ if (this.owns(run.goal)) this.disarm();
15313
+ this.publish(run.goal);
15314
+ }
15315
+ async reserve(sessionId, runId, offer, compaction) {
15316
+ const saved = await this.store.read(sessionId).catch((error) => {
15317
+ if (offer || this.activation) throw error;
15318
+ return null;
15319
+ });
15320
+ const initial = saved?.entry;
15321
+ if (initial?.claim)
15322
+ throw new GoalConflict(
15323
+ "A goal run is already reserved for this session.",
15324
+ "busy"
15325
+ );
15326
+ if (initial?.goal.status !== "active" || !this.owns(initial.goal)) {
15327
+ if (offer) throw new GoalConflict("Goal is no longer active.");
15328
+ return;
15329
+ }
15330
+ this.identity ??= getProcessIdentity2(process.pid, {
15331
+ canonicalEnvironment: true
15332
+ });
15333
+ const ownerIdentity = await this.identity;
15334
+ const run = await this.store.update(sessionId, (tx) => {
15335
+ if (offer) this.validateOffer(offer);
15336
+ const entry = tx.entry;
15337
+ if (entry?.claim)
15338
+ throw new GoalConflict(
15339
+ "A goal run is already reserved for this session.",
15340
+ "busy"
15341
+ );
15342
+ if (entry?.goal.status !== "active" || !this.owns(entry.goal)) {
15343
+ if (offer) throw new GoalConflict("Goal is no longer active.");
15344
+ return;
15345
+ }
15346
+ if (offer && (entry.goal.goal_id !== offer.goal_id || entry.goal.revision !== offer.revision || entry.goal.automatic_runs >= 3))
15347
+ throw new GoalConflict("Goal no longer accepts this continuation.");
15348
+ if (offer) {
15349
+ tx.consume(offer.continuation_id, entry.goal.goal_id, runId);
15350
+ entry.goal.automatic_runs += 1;
15351
+ }
15352
+ entry.claim = {
15353
+ run_id: runId,
15354
+ revision: entry.goal.revision,
15355
+ activation_id: entry.goal.activation_id,
15356
+ continuation_id: offer?.continuation_id,
15357
+ owner_pid: process.pid,
15358
+ owner_identity: ownerIdentity
15359
+ };
15360
+ return {
15361
+ goal: entry.goal,
15362
+ runId,
15363
+ continuationId: offer?.continuation_id,
15364
+ compaction
15365
+ };
15366
+ });
15367
+ if (run) {
15368
+ this.offer = null;
15369
+ this.activeRun = run;
15370
+ }
15371
+ return run;
15372
+ }
15373
+ tools(run) {
15374
+ return [
15375
+ defineTool22({
15376
+ name: "get_goal",
15377
+ description: "Read this run's session goal, including its objective, status, recorded tokens, and budget, or get {goal: null} if the run no longer holds the goal reservation.",
15378
+ input: z30.object({}),
15379
+ execute: async () => {
15380
+ const entry = (await this.store.read(run.goal.session_id)).entry;
15381
+ const goal = entry?.claim?.run_id === run.runId ? entry.goal : null;
15382
+ return {
15383
+ type: "json",
15384
+ value: { goal },
15385
+ display_content: goal ? `Goal (${goal.status.replaceAll("_", " ")})
15386
+ ${goal.objective}` : "This run no longer holds the goal reservation."
15387
+ };
15388
+ }
15389
+ }),
15390
+ defineTool22({
15391
+ name: "update_goal",
15392
+ description: "Report verified goal completion or a blocker that prevents further work before giving your final answer.",
15393
+ input: z30.object({
15394
+ status: z30.enum(["complete", "blocked"]).describe(
15395
+ "Use complete after verifying every goal requirement, or blocked when a concrete obstacle prevents further work. Omit the tool call for ordinary progress."
15396
+ ),
15397
+ evidence: z30.string().trim().min(1).max(2e3).describe(
15398
+ "For complete, state what you verified and the observed result. For blocked, state the obstacle and why it prevents further work."
15399
+ ),
15400
+ blocker_key: z30.string().trim().min(1).max(200).optional().describe(
15401
+ "Required for blocked. Reuse the same short key for the same obstacle across runs. Three consecutive goal runs reporting the same key stop the goal."
15402
+ )
15403
+ }),
15404
+ execute: (report) => {
15405
+ if (report.status === "blocked" && !report.blocker_key)
15406
+ throw new Error("blocked requires blocker_key");
15407
+ if (!this.owns(run.goal)) throw new Error("Goal stopped or changed");
15408
+ run.report = report;
15409
+ const label = report.status === "complete" ? "Completion" : "Blocker";
15410
+ return {
15411
+ type: "json",
15412
+ value: {
15413
+ recorded: true,
15414
+ applied_after_successful_finalization: true
15415
+ },
15416
+ display_content: `${label} report recorded for evaluation after successful finalization.
15417
+ ${report.evidence}`
15418
+ };
15419
+ }
15420
+ })
15421
+ ];
15422
+ }
15423
+ observer(run) {
15424
+ return {
15425
+ started: async (seq) => this.store.update(run.goal.session_id, ({ entry }) => {
15426
+ if (entry?.claim?.run_id !== run.runId)
15427
+ throw new Error("Goal run reservation missing");
15428
+ entry.claim.pending_seq = seq;
15429
+ }),
15430
+ completed: async (seq, usage, uncertain) => this.store.update(run.goal.session_id, ({ entry }) => {
15431
+ if (entry?.claim?.run_id !== run.runId)
15432
+ throw new Error("Goal run reservation missing");
15433
+ const claim = entry.claim;
15434
+ if (claim.accounted_seq !== void 0 && claim.accounted_seq >= seq)
15435
+ return;
15436
+ if (claim.pending_seq !== seq)
15437
+ throw new Error("Goal invocation is missing its reservation");
15438
+ const input = usage?.input_tokens;
15439
+ const cached = usage?.input_cached_tokens ?? 0;
15440
+ const output = usage?.output_tokens;
15441
+ const tokens = typeof input === "number" && typeof output === "number" && [input, cached, output].every(
15442
+ (value) => Number.isSafeInteger(value) && value >= 0
15443
+ ) && cached <= input ? input - cached + output : null;
15444
+ if (tokens !== null && Number.isSafeInteger(entry.goal.tokens_used + tokens))
15445
+ entry.goal.tokens_used += tokens;
15446
+ else entry.goal.usage_known = false;
15447
+ if (uncertain) entry.goal.usage_known = false;
15448
+ entry.goal.updated_at = stamp();
15449
+ claim.pending_seq = void 0;
15450
+ claim.accounted_seq = seq;
15451
+ })
15452
+ };
15453
+ }
15454
+ async finish(run, outcome, saved) {
15455
+ if (this.activeRun?.runId === run.runId) this.activeRun = void 0;
15456
+ const goal = await this.store.update(run.goal.session_id, ({ entry }) => {
15457
+ if (entry?.claim?.run_id !== run.runId) return null;
15458
+ if (entry.claim.pending_seq !== void 0) entry.goal.usage_known = false;
15459
+ entry.claim = void 0;
15460
+ const goal2 = entry.goal;
15461
+ if (goal2.status !== "active" || goal2.revision !== run.goal.revision || !this.owns(goal2))
15462
+ return goal2;
15463
+ if (!saved) transition(goal2, "paused", "checkpoint_failed");
15464
+ else if (outcome !== "completed")
15465
+ transition(
15466
+ goal2,
15467
+ "paused",
15468
+ outcome === "error" ? "run_error" : "interrupted"
15469
+ );
15470
+ else if (run.compaction) stopForBudget(goal2);
15471
+ else if (run.report?.status === "complete") transition(goal2, "complete");
15472
+ else {
15473
+ const key = run.report?.blocker_key;
15474
+ entry.blocker = key && run.report?.status === "blocked" ? {
15475
+ key,
15476
+ runs: entry.blocker?.key === key ? entry.blocker.runs + 1 : 1
15477
+ } : void 0;
15478
+ if ((entry.blocker?.runs ?? 0) >= 3) {
15479
+ transition(goal2, "blocked", "blocker");
15480
+ goal2.stop_detail = run.report?.evidence;
15481
+ } else if (!stopForBudget(goal2) && goal2.automatic_runs >= 3)
15482
+ transition(goal2, "paused", "turn_limit");
15483
+ }
15484
+ return goal2;
15485
+ });
15486
+ if (goal) {
15487
+ if (goal.status !== "active" && this.owns(goal)) this.disarm();
15488
+ this.publish(goal);
15489
+ }
15490
+ return goal;
15491
+ }
15492
+ };
15493
+
14947
15494
  // src/rpc/run-debug.ts
14948
15495
  import { stringifyContent } from "@codelia/core";
14949
15496
  var DEBUG_MAX_CONTENT_CHARS = 2e3;
@@ -15547,7 +16094,8 @@ var createRunHandlers = ({
15547
16094
  runEventStoreFactory,
15548
16095
  sessionStateStore,
15549
16096
  appendSession,
15550
- beforeRunStart
16097
+ beforeRunStart,
16098
+ goalStore
15551
16099
  }) => {
15552
16100
  let activeRunAbort = null;
15553
16101
  const steerAttachments = /* @__PURE__ */ new Map();
@@ -15556,6 +16104,18 @@ var createRunHandlers = ({
15556
16104
  steerAttachments.delete(steerId);
15557
16105
  };
15558
16106
  let runStartQueue = Promise.resolve();
16107
+ const goals = goalStore ? new GoalController(
16108
+ state,
16109
+ goalStore,
16110
+ sessionStateStore,
16111
+ () => resolveSessionWorkspaceRoot(state)
16112
+ ) : void 0;
16113
+ const serializeAdmission = (action) => {
16114
+ const admit = () => state.withAdmissionLock(action);
16115
+ const queued = runStartQueue.then(admit);
16116
+ runStartQueue = queued.catch(() => void 0);
16117
+ return queued;
16118
+ };
15559
16119
  let runSteerQueue = Promise.resolve();
15560
16120
  let sessionOpenSettled = Promise.resolve();
15561
16121
  const normalizeRuntimeAgentHistory = (label, runtimeAgent) => {
@@ -15614,24 +16174,34 @@ var createRunHandlers = ({
15614
16174
  ...final !== void 0 ? { final } : {}
15615
16175
  });
15616
16176
  };
15617
- const handleRunStart = (id, params) => {
16177
+ const handleRunStart = (id2, params, continuation) => {
15618
16178
  let admittedRunId = null;
15619
16179
  let responseSent = false;
16180
+ let admittedGoal;
15620
16181
  const run = async () => {
16182
+ let offer;
16183
+ if (continuation !== void 0 && goals) {
16184
+ try {
16185
+ offer = goals.validateOffer(continuation);
16186
+ } catch (error) {
16187
+ goals.reject(id2, error);
16188
+ return;
16189
+ }
16190
+ }
15621
16191
  let initialInput;
15622
16192
  try {
15623
16193
  initialInput = normalizeRunInput(params.input);
15624
16194
  } catch (error) {
15625
- sendError(id, {
15626
- code: RPC_ERROR_CODE11.INVALID_PARAMS,
16195
+ sendError(id2, {
16196
+ code: RPC_ERROR_CODE12.INVALID_PARAMS,
15627
16197
  message: String(error)
15628
16198
  });
15629
16199
  return;
15630
16200
  }
15631
16201
  const attachmentIds = runAttachmentIds(initialInput);
15632
16202
  if (params.force_compaction && attachmentIds.length > 0) {
15633
- sendError(id, {
15634
- code: RPC_ERROR_CODE11.INVALID_PARAMS,
16203
+ sendError(id2, {
16204
+ code: RPC_ERROR_CODE12.INVALID_PARAMS,
15635
16205
  message: "A compaction run cannot admit new attachments"
15636
16206
  });
15637
16207
  return;
@@ -15640,16 +16210,16 @@ var createRunHandlers = ({
15640
16210
  try {
15641
16211
  await beforeRunStart();
15642
16212
  } catch (error) {
15643
- sendError(id, {
15644
- code: RPC_ERROR_CODE11.RUNTIME_INTERNAL,
16213
+ sendError(id2, {
16214
+ code: RPC_ERROR_CODE12.RUNTIME_INTERNAL,
15645
16215
  message: `startup onboarding failed: ${String(error)}`
15646
16216
  });
15647
16217
  return;
15648
16218
  }
15649
16219
  }
15650
16220
  if (state.activeRunId) {
15651
- sendError(id, {
15652
- code: RPC_ERROR_CODE11.RUNTIME_BUSY,
16221
+ sendError(id2, {
16222
+ code: RPC_ERROR_CODE12.RUNTIME_BUSY,
15653
16223
  message: "runtime busy"
15654
16224
  });
15655
16225
  return;
@@ -15665,15 +16235,15 @@ var createRunHandlers = ({
15665
16235
  try {
15666
16236
  resumeState = await sessionStateStore.load(requestedSessionId);
15667
16237
  } catch (error) {
15668
- sendError(id, {
15669
- code: RPC_ERROR_CODE11.SESSION_LOAD_FAILED,
16238
+ sendError(id2, {
16239
+ code: RPC_ERROR_CODE12.SESSION_LOAD_FAILED,
15670
16240
  message: `session load failed: ${String(error)}`
15671
16241
  });
15672
16242
  return;
15673
16243
  }
15674
16244
  if (!resumeState) {
15675
- sendError(id, {
15676
- code: RPC_ERROR_CODE11.SESSION_NOT_FOUND,
16245
+ sendError(id2, {
16246
+ code: RPC_ERROR_CODE12.SESSION_NOT_FOUND,
15677
16247
  message: "session not found"
15678
16248
  });
15679
16249
  return;
@@ -15683,8 +16253,8 @@ var createRunHandlers = ({
15683
16253
  try {
15684
16254
  resumeState = await sessionStateStore.load(state.sessionId);
15685
16255
  } catch (error) {
15686
- sendError(id, {
15687
- code: RPC_ERROR_CODE11.SESSION_LOAD_FAILED,
16256
+ sendError(id2, {
16257
+ code: RPC_ERROR_CODE12.SESSION_LOAD_FAILED,
15688
16258
  message: `session reload failed: ${String(error)}`
15689
16259
  });
15690
16260
  return;
@@ -15694,8 +16264,8 @@ var createRunHandlers = ({
15694
16264
  }
15695
16265
  }
15696
16266
  if (resumeState?.meta?.codelia_subagent) {
15697
- sendError(id, {
15698
- code: RPC_ERROR_CODE11.INVALID_PARAMS,
16267
+ sendError(id2, {
16268
+ code: RPC_ERROR_CODE12.INVALID_PARAMS,
15699
16269
  message: "Delegated sessions cannot be resumed as a root run"
15700
16270
  });
15701
16271
  return;
@@ -15718,8 +16288,8 @@ var createRunHandlers = ({
15718
16288
  }
15719
16289
  } catch (error) {
15720
16290
  state.sessionModelOverride = previousModelOverride;
15721
- sendError(id, {
15722
- code: error instanceof AttachmentAdmissionError ? RPC_ERROR_CODE11.INVALID_PARAMS : RPC_ERROR_CODE11.RUNTIME_INTERNAL,
16291
+ sendError(id2, {
16292
+ code: error instanceof AttachmentAdmissionError ? RPC_ERROR_CODE12.INVALID_PARAMS : RPC_ERROR_CODE12.RUNTIME_INTERNAL,
15723
16293
  message: error instanceof Error ? error.message : String(error)
15724
16294
  });
15725
16295
  return;
@@ -15735,8 +16305,8 @@ var createRunHandlers = ({
15735
16305
  });
15736
16306
  } catch (error) {
15737
16307
  state.sessionModelOverride = previousModelOverride;
15738
- sendError(id, {
15739
- code: RPC_ERROR_CODE11.INVALID_PARAMS,
16308
+ sendError(id2, {
16309
+ code: RPC_ERROR_CODE12.INVALID_PARAMS,
15740
16310
  message: String(error)
15741
16311
  });
15742
16312
  return;
@@ -15748,8 +16318,8 @@ var createRunHandlers = ({
15748
16318
  });
15749
16319
  } catch {
15750
16320
  state.sessionModelOverride = previousModelOverride;
15751
- sendError(id, {
15752
- code: RPC_ERROR_CODE11.INVALID_PARAMS,
16321
+ sendError(id2, {
16322
+ code: RPC_ERROR_CODE12.INVALID_PARAMS,
15753
16323
  message: "Could not claim the attachments for this conversation. Upload them again."
15754
16324
  });
15755
16325
  return;
@@ -15782,6 +16352,7 @@ var createRunHandlers = ({
15782
16352
  state.sessionId = sessionId;
15783
16353
  }
15784
16354
  const switchedSession = previousSessionId !== sessionId;
16355
+ if (switchedSession) goals?.disarm();
15785
16356
  if (loadedSessionState && resumeState) {
15786
16357
  const restoredTodos = readTodosFromSessionMeta(resumeState.meta);
15787
16358
  if (restoredTodos.length > 0) {
@@ -15801,9 +16372,33 @@ var createRunHandlers = ({
15801
16372
  ...runMeta
15802
16373
  };
15803
16374
  }
16375
+ if (goals?.enabled) {
16376
+ try {
16377
+ admittedGoal = await goals.reserve(
16378
+ sessionId,
16379
+ runId,
16380
+ offer,
16381
+ params.force_compaction === true
16382
+ );
16383
+ if (admittedGoal && !goals.canStart(admittedGoal)) {
16384
+ await goals.finish(admittedGoal, "cancelled", true);
16385
+ throw new Error("Goal was paused before launch.");
16386
+ }
16387
+ } catch (error) {
16388
+ goals.reject(id2, error);
16389
+ return;
16390
+ }
16391
+ }
16392
+ const goalTools = goals && admittedGoal && !admittedGoal.compaction ? goals.tools(admittedGoal) : [];
16393
+ if (admittedGoal && state.tools?.some(
16394
+ (tool) => goalTools.some((goalTool) => goalTool.name === tool.name)
16395
+ ))
16396
+ throw new Error("Goal tool name conflicts with a runtime tool.");
15804
16397
  state.autoApprovedClientToolNames = new Set(
15805
16398
  (params.tools ?? []).filter((tool) => tool.approval === "never").map((tool) => tool.name)
15806
16399
  );
16400
+ for (const tool of goalTools)
16401
+ state.autoApprovedClientToolNames.add(tool.name);
15807
16402
  const startedAt = nowIso4();
15808
16403
  state.beginRun(runId, params.ui_context ?? state.lastUiContext);
15809
16404
  admittedRunId = runId;
@@ -15988,6 +16583,15 @@ var createRunHandlers = ({
15988
16583
  });
15989
16584
  appendSession({
15990
16585
  type: "run.start",
16586
+ ...offer ? { source: "goal" } : {},
16587
+ ...admittedGoal ? {
16588
+ goal: {
16589
+ goal_id: admittedGoal.goal.goal_id,
16590
+ revision: admittedGoal.goal.revision,
16591
+ activation_id: admittedGoal.goal.activation_id,
16592
+ ...offer ? { continuation_id: offer.continuation_id } : {}
16593
+ }
16594
+ } : {},
15991
16595
  run_id: runId,
15992
16596
  session_id: sessionId,
15993
16597
  ts: nowIso4(),
@@ -16007,13 +16611,14 @@ var createRunHandlers = ({
16007
16611
  session_id: sessionId,
16008
16612
  ...sessionStore.filePath ? { session_log_path: sessionStore.filePath } : {}
16009
16613
  };
16010
- sendResult(id, result);
16614
+ sendResult(id2, result);
16011
16615
  responseSent = true;
16012
16616
  log2(`run.start ${runId}`);
16013
16617
  emitRunStatus(runId, "running");
16014
16618
  void (async () => {
16015
16619
  let finalResponse;
16016
- let sessionSaveChain = Promise.resolve();
16620
+ let outcome = "error";
16621
+ let sessionSaveChain = Promise.resolve(true);
16017
16622
  let lastSessionSaveAt = 0;
16018
16623
  const polledUnconfirmedSteers = [];
16019
16624
  const emitRunSummaryDiagnostics = () => {
@@ -16043,9 +16648,9 @@ var createRunHandlers = ({
16043
16648
  }
16044
16649
  return { unconsumed_steer_ids: unconsumedSteerIds };
16045
16650
  };
16046
- const queueSessionSave = async (reason) => {
16651
+ const queueSessionSave = (reason) => {
16047
16652
  sessionSaveChain = sessionSaveChain.then(async () => {
16048
- if (!sessionId) return;
16653
+ if (!sessionId) return false;
16049
16654
  const messages = runtimeAgent.getHistoryMessages();
16050
16655
  const snapshotMessages = normalizeToolCallHistory(
16051
16656
  stripStartupSystemMessages(
@@ -16086,10 +16691,12 @@ var createRunHandlers = ({
16086
16691
  await sessionStateStore.save(snapshot);
16087
16692
  state.sessionMeta = sessionMetaWithResumeContext ?? null;
16088
16693
  logRunDebug(log2, runId, `session.save ${reason}`);
16694
+ return true;
16089
16695
  }).catch((error) => {
16090
16696
  log2(`Error: session-state save failed: ${String(error)}`);
16697
+ return false;
16091
16698
  });
16092
- await sessionSaveChain;
16699
+ return sessionSaveChain;
16093
16700
  };
16094
16701
  const maybeDebouncedSessionSave = () => {
16095
16702
  const now = Date.now();
@@ -16156,7 +16763,17 @@ var createRunHandlers = ({
16156
16763
  pollMessages,
16157
16764
  signal: runAbortController.signal,
16158
16765
  forceCompaction: params.force_compaction,
16159
- tools: clientTools,
16766
+ tools: goalTools.length ? [
16767
+ ...goalTools,
16768
+ ...(clientTools ?? []).filter(
16769
+ (tool) => !goalTools.some((owned) => owned.name === tool.name)
16770
+ )
16771
+ ] : clientTools,
16772
+ ...goals && admittedGoal ? {
16773
+ runContext: `${offer ? "Continue work on the session goal" : "Session goal"} (follow newer user instructions): ${JSON.stringify(admittedGoal.goal.objective)}.`,
16774
+ runtimeInitiated: Boolean(offer),
16775
+ modelCallObserver: goals.observer(admittedGoal)
16776
+ } : {},
16160
16777
  toolChoice: params.tool_choice,
16161
16778
  ...streamDeltas ? { streamDeltas: true } : {}
16162
16779
  })) {
@@ -16230,6 +16847,7 @@ var createRunHandlers = ({
16230
16847
  await queueSessionSave("terminal");
16231
16848
  emitRunSummaryDiagnostics();
16232
16849
  const status = state.cancelRequested ? "cancelled" : "completed";
16850
+ outcome = status;
16233
16851
  const terminalExtras = buildTerminalStatusExtras();
16234
16852
  emitRunStatus(runId, status, void 0, void 0, terminalExtras);
16235
16853
  emitRunEnd(
@@ -16242,6 +16860,7 @@ var createRunHandlers = ({
16242
16860
  deltaCoalescer?.dispose();
16243
16861
  const err = error instanceof Error ? error : new Error(String(error));
16244
16862
  if (state.cancelRequested || isAbortLikeError(err)) {
16863
+ outcome = "cancelled";
16245
16864
  normalizeRuntimeAgentHistory(`run.cancel ${runId}`, runtimeAgent);
16246
16865
  await queueSessionSave("cancelled");
16247
16866
  emitRunSummaryDiagnostics();
@@ -16282,40 +16901,53 @@ var createRunHandlers = ({
16282
16901
  if (state.cancelRequested) {
16283
16902
  normalizeRuntimeAgentHistory(`run.cancel ${runId}`, runtimeAgent);
16284
16903
  }
16285
- await queueSessionSave("finally");
16904
+ const saved = await queueSessionSave("finally");
16905
+ const goalRun = admittedGoal;
16906
+ const finalOutcome = state.cancelRequested ? "cancelled" : outcome === "completed" && finalResponse === void 0 ? "error" : outcome;
16907
+ const goal = goals && goalRun ? await goals.finish(goalRun, finalOutcome, saved).catch((error) => {
16908
+ goals.stopAfterStorageFailure(goalRun);
16909
+ log2(`goal accounting failed: ${String(error)}`);
16910
+ return null;
16911
+ }) : null;
16286
16912
  if (activeRunAbort?.runId === runId) {
16287
16913
  activeRunAbort = null;
16288
16914
  }
16289
16915
  state.finishRun(runId);
16916
+ if (goal) goals?.ready(goal, runId);
16290
16917
  }
16291
16918
  })();
16292
16919
  };
16293
- const admit = () => state.withAdmissionLock(run);
16294
- const queued = runStartQueue.then(admit, admit).catch((error) => {
16295
- if (admittedRunId) {
16296
- const runId = admittedRunId;
16297
- if (activeRunAbort?.runId === runId) activeRunAbort = null;
16298
- state.finishRun(runId);
16299
- if (responseSent) {
16300
- try {
16301
- sendRunStatus(state, runId, "error", "runtime start failed");
16302
- } catch {
16920
+ return serializeAdmission(async () => {
16921
+ try {
16922
+ await run();
16923
+ return;
16924
+ } catch (error) {
16925
+ if (goals && admittedGoal) {
16926
+ await goals.finish(admittedGoal, "error", true).catch((cleanupError) => {
16927
+ goals.disarm();
16928
+ log2(`goal admission cleanup failed: ${String(cleanupError)}`);
16929
+ });
16930
+ }
16931
+ if (admittedRunId) {
16932
+ const runId = admittedRunId;
16933
+ if (activeRunAbort?.runId === runId) activeRunAbort = null;
16934
+ state.finishRun(runId);
16935
+ if (responseSent) {
16936
+ try {
16937
+ sendRunStatus(state, runId, "error", "runtime start failed");
16938
+ } catch {
16939
+ }
16303
16940
  }
16304
16941
  }
16942
+ throw error;
16305
16943
  }
16306
- throw error;
16307
16944
  });
16308
- runStartQueue = queued.then(
16309
- () => void 0,
16310
- () => void 0
16311
- );
16312
- return queued;
16313
16945
  };
16314
- const handleRunSteer = (id, params) => {
16946
+ const handleRunSteer = (id2, params) => {
16315
16947
  const runId = typeof params?.run_id === "string" ? params.run_id.trim() : "";
16316
16948
  if (!runId) {
16317
- sendError(id, {
16318
- code: RPC_ERROR_CODE11.INVALID_PARAMS,
16949
+ sendError(id2, {
16950
+ code: RPC_ERROR_CODE12.INVALID_PARAMS,
16319
16951
  message: "run_id is required"
16320
16952
  });
16321
16953
  return Promise.resolve();
@@ -16324,15 +16956,15 @@ var createRunHandlers = ({
16324
16956
  try {
16325
16957
  initialInput = normalizeRunInput(params.input, "run.steer");
16326
16958
  } catch (error) {
16327
- sendError(id, {
16328
- code: RPC_ERROR_CODE11.INVALID_PARAMS,
16959
+ sendError(id2, {
16960
+ code: RPC_ERROR_CODE12.INVALID_PARAMS,
16329
16961
  message: String(error)
16330
16962
  });
16331
16963
  return Promise.resolve();
16332
16964
  }
16333
16965
  if (isRunInputEmpty(initialInput)) {
16334
- sendError(id, {
16335
- code: RPC_ERROR_CODE11.INVALID_PARAMS,
16966
+ sendError(id2, {
16967
+ code: RPC_ERROR_CODE12.INVALID_PARAMS,
16336
16968
  message: "run.steer input must not be empty"
16337
16969
  });
16338
16970
  return Promise.resolve();
@@ -16340,8 +16972,8 @@ var createRunHandlers = ({
16340
16972
  const clientSteerId = typeof params.client_steer_id === "string" && params.client_steer_id.trim() ? params.client_steer_id.trim() : void 0;
16341
16973
  const admitSteer = async () => {
16342
16974
  if (!state.canSteerRun(runId)) {
16343
- sendError(id, {
16344
- code: RPC_ERROR_CODE11.RUN_NOT_FOUND,
16975
+ sendError(id2, {
16976
+ code: RPC_ERROR_CODE12.RUN_NOT_FOUND,
16345
16977
  message: "active run not found"
16346
16978
  });
16347
16979
  return;
@@ -16366,8 +16998,8 @@ var createRunHandlers = ({
16366
16998
  if (state.prepareRunImages)
16367
16999
  normalizedInput = await state.prepareRunImages(normalizedInput);
16368
17000
  } catch (error) {
16369
- sendError(id, {
16370
- code: error instanceof AttachmentAdmissionError ? RPC_ERROR_CODE11.INVALID_PARAMS : RPC_ERROR_CODE11.RUNTIME_INTERNAL,
17001
+ sendError(id2, {
17002
+ code: error instanceof AttachmentAdmissionError ? RPC_ERROR_CODE12.INVALID_PARAMS : RPC_ERROR_CODE12.RUNTIME_INTERNAL,
16371
17003
  message: error instanceof Error ? error.message : String(error)
16372
17004
  });
16373
17005
  return;
@@ -16380,8 +17012,8 @@ var createRunHandlers = ({
16380
17012
  sessionId
16381
17013
  );
16382
17014
  } catch {
16383
- sendError(id, {
16384
- code: RPC_ERROR_CODE11.INVALID_PARAMS,
17015
+ sendError(id2, {
17016
+ code: RPC_ERROR_CODE12.INVALID_PARAMS,
16385
17017
  message: "Could not retain the attachments for this conversation. Upload them again."
16386
17018
  });
16387
17019
  return;
@@ -16389,8 +17021,8 @@ var createRunHandlers = ({
16389
17021
  }
16390
17022
  if (!state.canSteerRun(runId)) {
16391
17023
  releaseAttachments?.();
16392
- sendError(id, {
16393
- code: RPC_ERROR_CODE11.RUN_NOT_FOUND,
17024
+ sendError(id2, {
17025
+ code: RPC_ERROR_CODE12.RUN_NOT_FOUND,
16394
17026
  message: "active run ended before steer could be queued"
16395
17027
  });
16396
17028
  return;
@@ -16405,7 +17037,7 @@ var createRunHandlers = ({
16405
17037
  ids: attachmentIds,
16406
17038
  release: releaseAttachments
16407
17039
  });
16408
- sendResult(id, {
17040
+ sendResult(id2, {
16409
17041
  ok: true,
16410
17042
  steer_id: steerId
16411
17043
  });
@@ -16418,74 +17050,108 @@ var createRunHandlers = ({
16418
17050
  );
16419
17051
  return queued;
16420
17052
  };
16421
- const handleRunCancel = (id, params) => {
16422
- if (state.cancelRun(params.run_id)) {
16423
- if (activeRunAbort?.runId === params.run_id) {
16424
- activeRunAbort.controller.abort(
16425
- new Error(params.reason ?? "cancelled by user")
16426
- );
16427
- }
16428
- sendResult(id, { ok: true });
17053
+ const interruptRun = (runId, reason = "cancelled by user") => {
17054
+ if (!state.cancelRun(runId)) return false;
17055
+ if (activeRunAbort?.runId === runId)
17056
+ activeRunAbort.controller.abort(new Error(reason));
17057
+ return true;
17058
+ };
17059
+ const handleGoal = (id2, method, raw) => {
17060
+ if (!goals?.enabled) {
17061
+ sendError(id2, {
17062
+ code: RPC_ERROR_CODE12.INVALID_PARAMS,
17063
+ message: "Goals are unavailable on this connection."
17064
+ });
17065
+ return Promise.resolve();
17066
+ }
17067
+ if (method === "goal.continue") {
17068
+ const params = raw;
17069
+ return handleRunStart(
17070
+ id2,
17071
+ {
17072
+ input: { type: "text", text: "" },
17073
+ session_id: params?.session_id,
17074
+ tools: params?.tools,
17075
+ ui_context: params?.ui_context
17076
+ },
17077
+ raw ?? {}
17078
+ );
17079
+ }
17080
+ return goals.handle(
17081
+ id2,
17082
+ method,
17083
+ raw,
17084
+ serializeAdmission,
17085
+ interruptRun,
17086
+ (error) => log2(`goal operation failed: ${String(error)}`)
17087
+ );
17088
+ };
17089
+ const handleRunCancel = (id2, params) => {
17090
+ if (interruptRun(params.run_id, params.reason)) {
17091
+ sendResult(id2, { ok: true });
16429
17092
  log2(`run.cancel ${params.run_id} (${params.reason ?? "no reason"})`);
16430
17093
  return;
16431
17094
  }
16432
- sendError(id, {
16433
- code: RPC_ERROR_CODE11.RUN_NOT_FOUND,
17095
+ sendError(id2, {
17096
+ code: RPC_ERROR_CODE12.RUN_NOT_FOUND,
16434
17097
  message: "run not found"
16435
17098
  });
16436
17099
  };
16437
- const handleSessionOpen = (id, params) => {
17100
+ const handleSessionOpen = (id2, params) => {
17101
+ const sessionId = params?.session_id?.trim();
17102
+ if (sessionId && sessionId !== state.sessionId && !state.activeRunId)
17103
+ goals?.disarm();
16438
17104
  const open3 = async () => {
16439
- const sessionId = params?.session_id?.trim();
16440
17105
  if (!sessionId) {
16441
- sendError(id, {
16442
- code: RPC_ERROR_CODE11.INVALID_PARAMS,
17106
+ sendError(id2, {
17107
+ code: RPC_ERROR_CODE12.INVALID_PARAMS,
16443
17108
  message: "session_id is required"
16444
17109
  });
16445
17110
  return;
16446
17111
  }
16447
17112
  if (state.activeRunId) {
16448
- sendError(id, {
16449
- code: RPC_ERROR_CODE11.RUNTIME_BUSY,
17113
+ sendError(id2, {
17114
+ code: RPC_ERROR_CODE12.RUNTIME_BUSY,
16450
17115
  message: "runtime busy"
16451
17116
  });
16452
17117
  return;
16453
17118
  }
16454
17119
  if (sessionId === state.sessionId) {
16455
- sendResult(id, { session_id: sessionId });
17120
+ sendResult(id2, { session_id: sessionId });
16456
17121
  return;
16457
17122
  }
16458
17123
  let opened;
16459
17124
  try {
16460
17125
  opened = await sessionStateStore.load(sessionId);
16461
17126
  } catch (error) {
16462
- sendError(id, {
16463
- code: RPC_ERROR_CODE11.SESSION_LOAD_FAILED,
17127
+ sendError(id2, {
17128
+ code: RPC_ERROR_CODE12.SESSION_LOAD_FAILED,
16464
17129
  message: `session load failed: ${String(error)}`
16465
17130
  });
16466
17131
  return;
16467
17132
  }
16468
17133
  if (!opened) {
16469
- sendError(id, {
16470
- code: RPC_ERROR_CODE11.SESSION_NOT_FOUND,
17134
+ sendError(id2, {
17135
+ code: RPC_ERROR_CODE12.SESSION_NOT_FOUND,
16471
17136
  message: "session not found"
16472
17137
  });
16473
17138
  return;
16474
17139
  }
16475
17140
  if (opened.meta?.codelia_subagent) {
16476
- sendError(id, {
16477
- code: RPC_ERROR_CODE11.INVALID_PARAMS,
17141
+ sendError(id2, {
17142
+ code: RPC_ERROR_CODE12.INVALID_PARAMS,
16478
17143
  message: "Delegated sessions cannot be opened as a root session"
16479
17144
  });
16480
17145
  return;
16481
17146
  }
16482
17147
  state.attachments?.discardDraft();
17148
+ goals?.disarm();
16483
17149
  state.sessionId = sessionId;
16484
17150
  state.sessionMeta = toMetaObject(opened.meta) ?? null;
16485
17151
  state.sessionAppend = null;
16486
17152
  applySessionModelOverrideFromMeta(state, opened.meta);
16487
17153
  state.agent = null;
16488
- sendResult(id, { session_id: sessionId });
17154
+ sendResult(id2, { session_id: sessionId });
16489
17155
  log2(`session.open ${sessionId}`);
16490
17156
  };
16491
17157
  const queued = runStartQueue.then(open3, open3);
@@ -16498,6 +17164,7 @@ var createRunHandlers = ({
16498
17164
  };
16499
17165
  const afterSessionOpen = (task) => sessionOpenSettled.then(task);
16500
17166
  return {
17167
+ handleGoal,
16501
17168
  handleRunStart,
16502
17169
  handleRunSteer,
16503
17170
  handleRunCancel,
@@ -16508,26 +17175,26 @@ var createRunHandlers = ({
16508
17175
 
16509
17176
  // src/rpc/session-lifecycle.ts
16510
17177
  import {
16511
- RPC_ERROR_CODE as RPC_ERROR_CODE12
17178
+ RPC_ERROR_CODE as RPC_ERROR_CODE13
16512
17179
  } from "@codelia/protocol";
16513
- var createSessionUpdateHandler = (options) => async (id, params) => {
17180
+ var createSessionUpdateHandler = (options) => async (id2, params) => {
16514
17181
  if (!options.sessions.updateMetadata) {
16515
- sendError(id, {
16516
- code: RPC_ERROR_CODE12.INVALID_PARAMS,
17182
+ sendError(id2, {
17183
+ code: RPC_ERROR_CODE13.INVALID_PARAMS,
16517
17184
  message: "Session lifecycle updates are unavailable"
16518
17185
  });
16519
17186
  return;
16520
17187
  }
16521
17188
  if (!params || typeof params.session_id !== "string" || !/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/.test(params.session_id) || params.pinned !== void 0 && typeof params.pinned !== "boolean" || params.archived !== void 0 && typeof params.archived !== "boolean" || params.pinned === void 0 && params.archived === void 0) {
16522
- sendError(id, {
16523
- code: RPC_ERROR_CODE12.INVALID_PARAMS,
17189
+ sendError(id2, {
17190
+ code: RPC_ERROR_CODE13.INVALID_PARAMS,
16524
17191
  message: "Expected session_id and a boolean pinned or archived update"
16525
17192
  });
16526
17193
  return;
16527
17194
  }
16528
17195
  if (params.archived && options.state.activeRunId && options.state.sessionId === params.session_id) {
16529
- sendError(id, {
16530
- code: RPC_ERROR_CODE12.RUNTIME_BUSY,
17196
+ sendError(id2, {
17197
+ code: RPC_ERROR_CODE13.RUNTIME_BUSY,
16531
17198
  message: "Wait for the active run before archiving this session"
16532
17199
  });
16533
17200
  return;
@@ -16545,10 +17212,10 @@ var createSessionUpdateHandler = (options) => async (id, params) => {
16545
17212
  }
16546
17213
  }
16547
17214
  const result = { session };
16548
- sendResult(id, result);
17215
+ sendResult(id2, result);
16549
17216
  } catch (error) {
16550
- sendError(id, {
16551
- code: RPC_ERROR_CODE12.INVALID_PARAMS,
17217
+ sendError(id2, {
17218
+ code: RPC_ERROR_CODE13.INVALID_PARAMS,
16552
17219
  message: `Session update failed: ${String(error)}`
16553
17220
  });
16554
17221
  }
@@ -16557,7 +17224,7 @@ var createSessionUpdateHandler = (options) => async (id, params) => {
16557
17224
  // src/rpc/shell.ts
16558
17225
  import path19 from "path";
16559
17226
  import {
16560
- RPC_ERROR_CODE as RPC_ERROR_CODE13
17227
+ RPC_ERROR_CODE as RPC_ERROR_CODE14
16561
17228
  } from "@codelia/protocol";
16562
17229
  import {
16563
17230
  ToolOutputCacheStoreImpl as ToolOutputCacheStoreImpl3
@@ -16616,7 +17283,7 @@ var parseShellOutputRequest = (params) => {
16616
17283
  if (!taskId) {
16617
17284
  return {
16618
17285
  error: {
16619
- code: RPC_ERROR_CODE13.INVALID_PARAMS,
17286
+ code: RPC_ERROR_CODE14.INVALID_PARAMS,
16620
17287
  message: "task_id is required"
16621
17288
  }
16622
17289
  };
@@ -16624,7 +17291,7 @@ var parseShellOutputRequest = (params) => {
16624
17291
  if (params?.stream !== "stdout" && params?.stream !== "stderr") {
16625
17292
  return {
16626
17293
  error: {
16627
- code: RPC_ERROR_CODE13.INVALID_PARAMS,
17294
+ code: RPC_ERROR_CODE14.INVALID_PARAMS,
16628
17295
  message: "stream must be stdout or stderr"
16629
17296
  }
16630
17297
  };
@@ -16632,7 +17299,7 @@ var parseShellOutputRequest = (params) => {
16632
17299
  if (params.line_number !== void 0 && (params.offset !== void 0 || params.limit !== void 0)) {
16633
17300
  return {
16634
17301
  error: {
16635
- code: RPC_ERROR_CODE13.INVALID_PARAMS,
17302
+ code: RPC_ERROR_CODE14.INVALID_PARAMS,
16636
17303
  message: "line_number cannot be combined with offset or limit"
16637
17304
  }
16638
17305
  };
@@ -16640,7 +17307,7 @@ var parseShellOutputRequest = (params) => {
16640
17307
  if (params.line_number === void 0 && (params.char_offset !== void 0 || params.char_limit !== void 0)) {
16641
17308
  return {
16642
17309
  error: {
16643
- code: RPC_ERROR_CODE13.INVALID_PARAMS,
17310
+ code: RPC_ERROR_CODE14.INVALID_PARAMS,
16644
17311
  message: "char_offset/char_limit require line_number"
16645
17312
  }
16646
17313
  };
@@ -16648,7 +17315,7 @@ var parseShellOutputRequest = (params) => {
16648
17315
  if (params.offset !== void 0 && (!Number.isFinite(params.offset) || params.offset < 0)) {
16649
17316
  return {
16650
17317
  error: {
16651
- code: RPC_ERROR_CODE13.INVALID_PARAMS,
17318
+ code: RPC_ERROR_CODE14.INVALID_PARAMS,
16652
17319
  message: "offset must be a non-negative number"
16653
17320
  }
16654
17321
  };
@@ -16656,7 +17323,7 @@ var parseShellOutputRequest = (params) => {
16656
17323
  if (params.limit !== void 0 && (!Number.isFinite(params.limit) || params.limit <= 0)) {
16657
17324
  return {
16658
17325
  error: {
16659
- code: RPC_ERROR_CODE13.INVALID_PARAMS,
17326
+ code: RPC_ERROR_CODE14.INVALID_PARAMS,
16660
17327
  message: "limit must be a positive number"
16661
17328
  }
16662
17329
  };
@@ -16664,7 +17331,7 @@ var parseShellOutputRequest = (params) => {
16664
17331
  if (params.line_number !== void 0 && (!Number.isFinite(params.line_number) || params.line_number <= 0)) {
16665
17332
  return {
16666
17333
  error: {
16667
- code: RPC_ERROR_CODE13.INVALID_PARAMS,
17334
+ code: RPC_ERROR_CODE14.INVALID_PARAMS,
16668
17335
  message: "line_number must be a positive number"
16669
17336
  }
16670
17337
  };
@@ -16672,7 +17339,7 @@ var parseShellOutputRequest = (params) => {
16672
17339
  if (params.char_offset !== void 0 && (!Number.isFinite(params.char_offset) || params.char_offset < 0)) {
16673
17340
  return {
16674
17341
  error: {
16675
- code: RPC_ERROR_CODE13.INVALID_PARAMS,
17342
+ code: RPC_ERROR_CODE14.INVALID_PARAMS,
16676
17343
  message: "char_offset must be a non-negative number"
16677
17344
  }
16678
17345
  };
@@ -16680,7 +17347,7 @@ var parseShellOutputRequest = (params) => {
16680
17347
  if (params.char_limit !== void 0 && (!Number.isFinite(params.char_limit) || params.char_limit <= 0)) {
16681
17348
  return {
16682
17349
  error: {
16683
- code: RPC_ERROR_CODE13.INVALID_PARAMS,
17350
+ code: RPC_ERROR_CODE14.INVALID_PARAMS,
16684
17351
  message: "char_limit must be a positive number"
16685
17352
  }
16686
17353
  };
@@ -16734,7 +17401,7 @@ var parseTaskId = (value) => {
16734
17401
  var toTaskRpcError = (error) => {
16735
17402
  if (!(error instanceof TaskManagerError)) {
16736
17403
  return {
16737
- code: RPC_ERROR_CODE13.RUNTIME_INTERNAL,
17404
+ code: RPC_ERROR_CODE14.RUNTIME_INTERNAL,
16738
17405
  message: String(error)
16739
17406
  };
16740
17407
  }
@@ -16743,24 +17410,24 @@ var toTaskRpcError = (error) => {
16743
17410
  case "invalid_task_id":
16744
17411
  case "unsupported_workspace_mode":
16745
17412
  return {
16746
- code: RPC_ERROR_CODE13.INVALID_PARAMS,
17413
+ code: RPC_ERROR_CODE14.INVALID_PARAMS,
16747
17414
  message: error.message
16748
17415
  };
16749
17416
  case "manager_shutting_down":
16750
17417
  return {
16751
- code: RPC_ERROR_CODE13.RUNTIME_BUSY,
17418
+ code: RPC_ERROR_CODE14.RUNTIME_BUSY,
16752
17419
  message: error.message
16753
17420
  };
16754
17421
  default:
16755
17422
  return {
16756
- code: RPC_ERROR_CODE13.RUNTIME_INTERNAL,
17423
+ code: RPC_ERROR_CODE14.RUNTIME_INTERNAL,
16757
17424
  message: error.message
16758
17425
  };
16759
17426
  }
16760
17427
  };
16761
- var sendTaskError = (id, error) => {
17428
+ var sendTaskError = (id2, error) => {
16762
17429
  const rpcError = toTaskRpcError(error);
16763
- sendError(id, rpcError);
17430
+ sendError(id2, rpcError);
16764
17431
  };
16765
17432
  var requireShellTask = async (taskManager, taskId) => {
16766
17433
  const task = await taskManager.status(taskId);
@@ -16777,7 +17444,7 @@ var resolveShellTimeoutSeconds2 = (requestedTimeout, background) => {
16777
17444
  if (!Number.isFinite(requestedTimeout) || requestedTimeout <= 0) {
16778
17445
  return {
16779
17446
  error: {
16780
- code: RPC_ERROR_CODE13.INVALID_PARAMS,
17447
+ code: RPC_ERROR_CODE14.INVALID_PARAMS,
16781
17448
  message: "timeout_seconds must be a positive number"
16782
17449
  }
16783
17450
  };
@@ -16791,7 +17458,7 @@ var resolveShellTimeoutSeconds2 = (requestedTimeout, background) => {
16791
17458
  if (requestedTimeout > MAX_EXECUTION_TIMEOUT_SECONDS) {
16792
17459
  return {
16793
17460
  error: {
16794
- code: RPC_ERROR_CODE13.INVALID_PARAMS,
17461
+ code: RPC_ERROR_CODE14.INVALID_PARAMS,
16795
17462
  message: `background timeout_seconds must be ${MAX_EXECUTION_TIMEOUT_SECONDS} or less; omit timeout_seconds to run without an execution timer`
16796
17463
  }
16797
17464
  };
@@ -16805,7 +17472,7 @@ var resolveShellWaitTimeoutSeconds2 = (requestedTimeout) => {
16805
17472
  if (!Number.isFinite(requestedTimeout) || requestedTimeout <= 0) {
16806
17473
  return {
16807
17474
  error: {
16808
- code: RPC_ERROR_CODE13.INVALID_PARAMS,
17475
+ code: RPC_ERROR_CODE14.INVALID_PARAMS,
16809
17476
  message: "wait_timeout_seconds must be a positive number"
16810
17477
  }
16811
17478
  };
@@ -16813,7 +17480,7 @@ var resolveShellWaitTimeoutSeconds2 = (requestedTimeout) => {
16813
17480
  if (requestedTimeout > MAX_TIMEOUT_SECONDS) {
16814
17481
  return {
16815
17482
  error: {
16816
- code: RPC_ERROR_CODE13.INVALID_PARAMS,
17483
+ code: RPC_ERROR_CODE14.INVALID_PARAMS,
16817
17484
  message: `wait_timeout_seconds must be ${MAX_TIMEOUT_SECONDS} seconds or less`
16818
17485
  }
16819
17486
  };
@@ -16828,7 +17495,7 @@ var parseShellStartRequest = (state, params, options) => {
16828
17495
  if (!command) {
16829
17496
  return {
16830
17497
  error: {
16831
- code: RPC_ERROR_CODE13.INVALID_PARAMS,
17498
+ code: RPC_ERROR_CODE14.INVALID_PARAMS,
16832
17499
  message: "command is required"
16833
17500
  }
16834
17501
  };
@@ -16844,7 +17511,7 @@ var parseShellStartRequest = (state, params, options) => {
16844
17511
  if (!cwd) {
16845
17512
  return {
16846
17513
  error: {
16847
- code: RPC_ERROR_CODE13.INVALID_PARAMS,
17514
+ code: RPC_ERROR_CODE14.INVALID_PARAMS,
16848
17515
  message: "cwd is outside sandbox root"
16849
17516
  }
16850
17517
  };
@@ -16906,40 +17573,40 @@ var createShellHandlers = ({
16906
17573
  );
16907
17574
  return { task, commandPreview: parsed.commandPreview };
16908
17575
  };
16909
- const handleShellExec = async (id, params) => {
17576
+ const handleShellExec = async (id2, params) => {
16910
17577
  try {
16911
17578
  const { task, commandPreview } = await spawnShell(params, "shell.exec");
16912
17579
  const finished = await shellTaskManager.wait(task.task_id);
16913
17580
  const result = toShellExecResult(commandPreview, finished.result);
16914
- sendResult(id, result);
17581
+ sendResult(id2, result);
16915
17582
  log2(
16916
17583
  `shell.exec.done origin=ui_bang duration_ms=${result.duration_ms} exit_code=${String(result.exit_code)} signal=${result.signal ?? "-"}`
16917
17584
  );
16918
17585
  } catch (error) {
16919
17586
  if (typeof error === "object" && error !== null && "code" in error && "message" in error) {
16920
- sendError(id, error);
17587
+ sendError(id2, error);
16921
17588
  return;
16922
17589
  }
16923
- sendTaskError(id, error);
17590
+ sendTaskError(id2, error);
16924
17591
  }
16925
17592
  };
16926
- const handleShellStart = async (id, params) => {
17593
+ const handleShellStart = async (id2, params) => {
16927
17594
  try {
16928
17595
  const { task } = await spawnShell(params, "shell.start");
16929
- sendResult(id, toShellTaskInfo(task));
17596
+ sendResult(id2, toShellTaskInfo(task));
16930
17597
  } catch (error) {
16931
17598
  if (typeof error === "object" && error !== null && "code" in error && "message" in error) {
16932
- sendError(id, error);
17599
+ sendError(id2, error);
16933
17600
  return;
16934
17601
  }
16935
- sendTaskError(id, error);
17602
+ sendTaskError(id2, error);
16936
17603
  }
16937
17604
  };
16938
- const handleShellList = async (id, params) => {
17605
+ const handleShellList = async (id2, params) => {
16939
17606
  const requestedLimit = params?.limit;
16940
17607
  if (requestedLimit !== void 0 && (!Number.isFinite(requestedLimit) || requestedLimit <= 0)) {
16941
- sendError(id, {
16942
- code: RPC_ERROR_CODE13.INVALID_PARAMS,
17608
+ sendError(id2, {
17609
+ code: RPC_ERROR_CODE14.INVALID_PARAMS,
16943
17610
  message: "limit must be a positive number"
16944
17611
  });
16945
17612
  return;
@@ -16948,31 +17615,31 @@ var createShellHandlers = ({
16948
17615
  const limit = requestedLimit ? Math.trunc(requestedLimit) : void 0;
16949
17616
  const tasks = (await shellTaskManager.list()).filter((task) => task.kind === "shell").slice(0, limit).map(toShellTaskInfo);
16950
17617
  const result = { tasks };
16951
- sendResult(id, result);
17618
+ sendResult(id2, result);
16952
17619
  } catch (error) {
16953
- sendTaskError(id, error);
17620
+ sendTaskError(id2, error);
16954
17621
  }
16955
17622
  };
16956
- const handleShellStatus = async (id, params) => {
17623
+ const handleShellStatus = async (id2, params) => {
16957
17624
  const taskId = parseTaskId(params?.task_id);
16958
17625
  if (!taskId) {
16959
- sendError(id, {
16960
- code: RPC_ERROR_CODE13.INVALID_PARAMS,
17626
+ sendError(id2, {
17627
+ code: RPC_ERROR_CODE14.INVALID_PARAMS,
16961
17628
  message: "task_id is required"
16962
17629
  });
16963
17630
  return;
16964
17631
  }
16965
17632
  try {
16966
17633
  const task = await requireShellTask(shellTaskManager, taskId);
16967
- sendResult(id, toShellTaskInfo(task));
17634
+ sendResult(id2, toShellTaskInfo(task));
16968
17635
  } catch (error) {
16969
- sendTaskError(id, error);
17636
+ sendTaskError(id2, error);
16970
17637
  }
16971
17638
  };
16972
- const handleShellOutput = async (id, params) => {
17639
+ const handleShellOutput = async (id2, params) => {
16973
17640
  const parsed = parseShellOutputRequest(params);
16974
17641
  if ("error" in parsed) {
16975
- sendError(id, parsed.error);
17642
+ sendError(id2, parsed.error);
16976
17643
  return;
16977
17644
  }
16978
17645
  try {
@@ -16984,8 +17651,8 @@ var createShellHandlers = ({
16984
17651
  parsed.stream
16985
17652
  );
16986
17653
  if (!cacheId && liveContent === null && !isTerminalTaskState(task.state)) {
16987
- sendError(id, {
16988
- code: RPC_ERROR_CODE13.RUNTIME_BUSY,
17654
+ sendError(id2, {
17655
+ code: RPC_ERROR_CODE14.RUNTIME_BUSY,
16989
17656
  message: `shell output is not retained yet for running task: ${parsed.taskId}`
16990
17657
  });
16991
17658
  return;
@@ -17013,16 +17680,16 @@ var createShellHandlers = ({
17013
17680
  content,
17014
17681
  ...cacheId ? { ref_id: cacheId } : {}
17015
17682
  };
17016
- sendResult(id, result);
17683
+ sendResult(id2, result);
17017
17684
  } catch (error) {
17018
- sendTaskError(id, error);
17685
+ sendTaskError(id2, error);
17019
17686
  }
17020
17687
  };
17021
- const handleShellWait = async (id, params) => {
17688
+ const handleShellWait = async (id2, params) => {
17022
17689
  const taskId = parseTaskId(params?.task_id);
17023
17690
  if (!taskId) {
17024
- sendError(id, {
17025
- code: RPC_ERROR_CODE13.INVALID_PARAMS,
17691
+ sendError(id2, {
17692
+ code: RPC_ERROR_CODE14.INVALID_PARAMS,
17026
17693
  message: "task_id is required"
17027
17694
  });
17028
17695
  return;
@@ -17031,13 +17698,13 @@ var createShellHandlers = ({
17031
17698
  params?.wait_timeout_seconds
17032
17699
  );
17033
17700
  if (typeof waitTimeoutSeconds === "object") {
17034
- sendError(id, waitTimeoutSeconds.error);
17701
+ sendError(id2, waitTimeoutSeconds.error);
17035
17702
  return;
17036
17703
  }
17037
17704
  try {
17038
17705
  const existing = await requireShellTask(shellTaskManager, taskId);
17039
17706
  if (isTerminalTaskState(existing.state)) {
17040
- sendResult(id, toShellTaskInfo(existing));
17707
+ sendResult(id2, toShellTaskInfo(existing));
17041
17708
  return;
17042
17709
  }
17043
17710
  const controller = new AbortController();
@@ -17077,12 +17744,12 @@ var createShellHandlers = ({
17077
17744
  timeoutPromise
17078
17745
  ]);
17079
17746
  if (outcome.type === "detached") {
17080
- sendResult(id, outcome.result);
17747
+ sendResult(id2, outcome.result);
17081
17748
  return;
17082
17749
  }
17083
17750
  if (outcome.type === "still_running") {
17084
17751
  const task = await requireShellTask(shellTaskManager, taskId);
17085
- sendResult(id, {
17752
+ sendResult(id2, {
17086
17753
  ...toShellTaskInfo(task),
17087
17754
  ...isTerminalTaskState(task.state) ? {} : { still_running: true }
17088
17755
  });
@@ -17091,7 +17758,7 @@ var createShellHandlers = ({
17091
17758
  if (outcome.type === "aborted") {
17092
17759
  return;
17093
17760
  }
17094
- sendResult(id, toShellTaskInfo(outcome.task));
17761
+ sendResult(id2, toShellTaskInfo(outcome.task));
17095
17762
  } finally {
17096
17763
  if (timeoutHandle) {
17097
17764
  clearTimeout(timeoutHandle);
@@ -17099,14 +17766,14 @@ var createShellHandlers = ({
17099
17766
  unregister();
17100
17767
  }
17101
17768
  } catch (error) {
17102
- sendTaskError(id, error);
17769
+ sendTaskError(id2, error);
17103
17770
  }
17104
17771
  };
17105
- const handleShellDetach = async (id, params) => {
17772
+ const handleShellDetach = async (id2, params) => {
17106
17773
  const taskId = parseTaskId(params?.task_id);
17107
17774
  if (!taskId) {
17108
- sendError(id, {
17109
- code: RPC_ERROR_CODE13.INVALID_PARAMS,
17775
+ sendError(id2, {
17776
+ code: RPC_ERROR_CODE14.INVALID_PARAMS,
17110
17777
  message: "task_id is required"
17111
17778
  });
17112
17779
  return;
@@ -17115,8 +17782,8 @@ var createShellHandlers = ({
17115
17782
  const task = await requireShellTask(shellTaskManager, taskId);
17116
17783
  const waits = activeShellWaits.get(taskId);
17117
17784
  if (!waits || waits.size === 0) {
17118
- sendError(id, {
17119
- code: RPC_ERROR_CODE13.INVALID_PARAMS,
17785
+ sendError(id2, {
17786
+ code: RPC_ERROR_CODE14.INVALID_PARAMS,
17120
17787
  message: `no active shell.wait to detach for task: ${taskId}`
17121
17788
  });
17122
17789
  return;
@@ -17129,16 +17796,16 @@ var createShellHandlers = ({
17129
17796
  detached: true,
17130
17797
  state: task.state
17131
17798
  };
17132
- sendResult(id, result);
17799
+ sendResult(id2, result);
17133
17800
  } catch (error) {
17134
- sendTaskError(id, error);
17801
+ sendTaskError(id2, error);
17135
17802
  }
17136
17803
  };
17137
- const handleShellCancel = async (id, params) => {
17804
+ const handleShellCancel = async (id2, params) => {
17138
17805
  const taskId = parseTaskId(params?.task_id);
17139
17806
  if (!taskId) {
17140
- sendError(id, {
17141
- code: RPC_ERROR_CODE13.INVALID_PARAMS,
17807
+ sendError(id2, {
17808
+ code: RPC_ERROR_CODE14.INVALID_PARAMS,
17142
17809
  message: "task_id is required"
17143
17810
  });
17144
17811
  return;
@@ -17148,9 +17815,9 @@ var createShellHandlers = ({
17148
17815
  const task = await shellTaskManager.cancel(taskId, {
17149
17816
  reason: "cancelled"
17150
17817
  });
17151
- sendResult(id, toShellTaskInfo(task));
17818
+ sendResult(id2, toShellTaskInfo(task));
17152
17819
  } catch (error) {
17153
- sendTaskError(id, error);
17820
+ sendTaskError(id2, error);
17154
17821
  }
17155
17822
  };
17156
17823
  return {
@@ -17168,20 +17835,20 @@ var createShellHandlers = ({
17168
17835
  // src/rpc/skills.ts
17169
17836
  import path20 from "path";
17170
17837
  import {
17171
- RPC_ERROR_CODE as RPC_ERROR_CODE14
17838
+ RPC_ERROR_CODE as RPC_ERROR_CODE15
17172
17839
  } from "@codelia/protocol";
17173
17840
  var createSkillsHandlers = ({
17174
17841
  state,
17175
17842
  log: log2
17176
17843
  }) => {
17177
- const handleSkillsList = async (id, params) => {
17844
+ const handleSkillsList = async (id2, params) => {
17178
17845
  const requestedCwd = params?.cwd ? path20.resolve(params.cwd) : void 0;
17179
17846
  const workingDir = requestedCwd ?? state.runtimeWorkingDir ?? state.lastUiContext?.cwd ?? process.cwd();
17180
17847
  const forceReload = params?.force_reload ?? false;
17181
17848
  if (!forceReload) {
17182
17849
  const cachedCatalog = state.skillsCatalogByCwd.get(workingDir);
17183
17850
  if (cachedCatalog) {
17184
- sendResult(id, {
17851
+ sendResult(id2, {
17185
17852
  skills: cachedCatalog.skills,
17186
17853
  errors: cachedCatalog.errors,
17187
17854
  truncated: cachedCatalog.truncated
@@ -17198,8 +17865,8 @@ var createSkillsHandlers = ({
17198
17865
  config: await resolveEnvironmentSkillsConfig(state, workingDir)
17199
17866
  });
17200
17867
  } catch (error) {
17201
- sendError(id, {
17202
- code: RPC_ERROR_CODE14.RUNTIME_INTERNAL,
17868
+ sendError(id2, {
17869
+ code: RPC_ERROR_CODE15.RUNTIME_INTERNAL,
17203
17870
  message: `skills resolver init failed: ${String(error)}`
17204
17871
  });
17205
17872
  return;
@@ -17217,11 +17884,11 @@ var createSkillsHandlers = ({
17217
17884
  errors: catalog.errors,
17218
17885
  truncated: catalog.truncated
17219
17886
  };
17220
- sendResult(id, result);
17887
+ sendResult(id2, result);
17221
17888
  } catch (error) {
17222
17889
  log2(`skills.list error: ${String(error)}`);
17223
- sendError(id, {
17224
- code: RPC_ERROR_CODE14.RUNTIME_INTERNAL,
17890
+ sendError(id2, {
17891
+ code: RPC_ERROR_CODE15.RUNTIME_INTERNAL,
17225
17892
  message: `skills list failed: ${String(error)}`
17226
17893
  });
17227
17894
  }
@@ -17232,13 +17899,13 @@ var createSkillsHandlers = ({
17232
17899
  // src/rpc/task.ts
17233
17900
  import path21 from "path";
17234
17901
  import {
17235
- RPC_ERROR_CODE as RPC_ERROR_CODE16
17902
+ RPC_ERROR_CODE as RPC_ERROR_CODE17
17236
17903
  } from "@codelia/protocol";
17237
17904
  import { ToolOutputCacheStoreImpl as ToolOutputCacheStoreImpl4 } from "@codelia/storage";
17238
17905
 
17239
17906
  // src/rpc/tool.ts
17240
17907
  import {
17241
- RPC_ERROR_CODE as RPC_ERROR_CODE15
17908
+ RPC_ERROR_CODE as RPC_ERROR_CODE16
17242
17909
  } from "@codelia/protocol";
17243
17910
  var normalizeToolResult = (result) => {
17244
17911
  switch (result.type) {
@@ -17271,18 +17938,18 @@ var createToolHandlers = ({
17271
17938
  state,
17272
17939
  getAgent
17273
17940
  }) => {
17274
- const handleToolCall = async (id, params) => {
17941
+ const handleToolCall = async (id2, params) => {
17275
17942
  const toolName = params?.name;
17276
17943
  if (!toolName) {
17277
- sendError(id, {
17278
- code: RPC_ERROR_CODE15.INVALID_PARAMS,
17944
+ sendError(id2, {
17945
+ code: RPC_ERROR_CODE16.INVALID_PARAMS,
17279
17946
  message: "tool name is required"
17280
17947
  });
17281
17948
  return;
17282
17949
  }
17283
17950
  if (toolName === "attachment_read" && state.attachments) {
17284
- sendError(id, {
17285
- code: RPC_ERROR_CODE15.INVALID_PARAMS,
17951
+ sendError(id2, {
17952
+ code: RPC_ERROR_CODE16.INVALID_PARAMS,
17286
17953
  message: "attachment_read is only available during a model run"
17287
17954
  });
17288
17955
  return;
@@ -17292,8 +17959,8 @@ var createToolHandlers = ({
17292
17959
  }
17293
17960
  const tool = state.tools?.find((entry) => entry.name === toolName);
17294
17961
  if (!tool) {
17295
- sendError(id, {
17296
- code: RPC_ERROR_CODE15.INVALID_PARAMS,
17962
+ sendError(id2, {
17963
+ code: RPC_ERROR_CODE16.INVALID_PARAMS,
17297
17964
  message: `unknown tool: ${toolName}`
17298
17965
  });
17299
17966
  return;
@@ -17307,10 +17974,10 @@ var createToolHandlers = ({
17307
17974
  ok: true,
17308
17975
  result: normalizeToolResult(result)
17309
17976
  };
17310
- sendResult(id, response);
17977
+ sendResult(id2, response);
17311
17978
  } catch (error) {
17312
- sendError(id, {
17313
- code: RPC_ERROR_CODE15.RUNTIME_INTERNAL,
17979
+ sendError(id2, {
17980
+ code: RPC_ERROR_CODE16.RUNTIME_INTERNAL,
17314
17981
  message: `tool call failed: ${String(error)}`
17315
17982
  });
17316
17983
  }
@@ -17373,7 +18040,7 @@ var parseTaskId2 = (value) => {
17373
18040
  var toTaskRpcError2 = (error) => {
17374
18041
  if (!(error instanceof TaskManagerError)) {
17375
18042
  return {
17376
- code: RPC_ERROR_CODE16.RUNTIME_INTERNAL,
18043
+ code: RPC_ERROR_CODE17.RUNTIME_INTERNAL,
17377
18044
  message: String(error)
17378
18045
  };
17379
18046
  }
@@ -17382,23 +18049,23 @@ var toTaskRpcError2 = (error) => {
17382
18049
  case "invalid_task_id":
17383
18050
  case "unsupported_workspace_mode":
17384
18051
  return {
17385
- code: RPC_ERROR_CODE16.INVALID_PARAMS,
18052
+ code: RPC_ERROR_CODE17.INVALID_PARAMS,
17386
18053
  message: error.message
17387
18054
  };
17388
18055
  case "manager_shutting_down":
17389
18056
  return {
17390
- code: RPC_ERROR_CODE16.RUNTIME_BUSY,
18057
+ code: RPC_ERROR_CODE17.RUNTIME_BUSY,
17391
18058
  message: error.message
17392
18059
  };
17393
18060
  default:
17394
18061
  return {
17395
- code: RPC_ERROR_CODE16.RUNTIME_INTERNAL,
18062
+ code: RPC_ERROR_CODE17.RUNTIME_INTERNAL,
17396
18063
  message: error.message
17397
18064
  };
17398
18065
  }
17399
18066
  };
17400
- var sendTaskError2 = (id, error) => {
17401
- sendError(id, toTaskRpcError2(error));
18067
+ var sendTaskError2 = (id2, error) => {
18068
+ sendError(id2, toTaskRpcError2(error));
17402
18069
  };
17403
18070
  var toTaskSummary = (task, progress) => ({
17404
18071
  name: task.subagent?.name,
@@ -17444,7 +18111,7 @@ var resolveShellTimeoutSeconds3 = (requestedTimeout, background) => {
17444
18111
  if (!Number.isFinite(requestedTimeout) || requestedTimeout <= 0) {
17445
18112
  return {
17446
18113
  error: {
17447
- code: RPC_ERROR_CODE16.INVALID_PARAMS,
18114
+ code: RPC_ERROR_CODE17.INVALID_PARAMS,
17448
18115
  message: "timeout_seconds must be a positive number"
17449
18116
  }
17450
18117
  };
@@ -17458,7 +18125,7 @@ var resolveShellTimeoutSeconds3 = (requestedTimeout, background) => {
17458
18125
  if (requestedTimeout > MAX_EXECUTION_TIMEOUT_SECONDS) {
17459
18126
  return {
17460
18127
  error: {
17461
- code: RPC_ERROR_CODE16.INVALID_PARAMS,
18128
+ code: RPC_ERROR_CODE17.INVALID_PARAMS,
17462
18129
  message: `background timeout_seconds must be ${MAX_EXECUTION_TIMEOUT_SECONDS} or less; omit timeout_seconds to run without an execution timer`
17463
18130
  }
17464
18131
  };
@@ -17473,7 +18140,7 @@ var parseShellSpawnRequest = (state, params, options) => {
17473
18140
  if (!command) {
17474
18141
  return {
17475
18142
  error: {
17476
- code: RPC_ERROR_CODE16.INVALID_PARAMS,
18143
+ code: RPC_ERROR_CODE17.INVALID_PARAMS,
17477
18144
  message: "command is required for shell tasks"
17478
18145
  }
17479
18146
  };
@@ -17489,7 +18156,7 @@ var parseShellSpawnRequest = (state, params, options) => {
17489
18156
  if (!cwd) {
17490
18157
  return {
17491
18158
  error: {
17492
- code: RPC_ERROR_CODE16.INVALID_PARAMS,
18159
+ code: RPC_ERROR_CODE17.INVALID_PARAMS,
17493
18160
  message: "cwd is outside sandbox root"
17494
18161
  }
17495
18162
  };
@@ -17567,10 +18234,10 @@ var createTaskHandlers = ({
17567
18234
  if (task?.kind === "subagent" && task.subagent?.owner_session_id !== state.sessionId)
17568
18235
  throw new TaskManagerError("task_not_found", "Task not found");
17569
18236
  };
17570
- const handleTaskSpawn = async (id, params) => {
18237
+ const handleTaskSpawn = async (id2, params) => {
17571
18238
  if (!params || !isTaskKind(params.kind)) {
17572
- sendError(id, {
17573
- code: RPC_ERROR_CODE16.INVALID_PARAMS,
18239
+ sendError(id2, {
18240
+ code: RPC_ERROR_CODE17.INVALID_PARAMS,
17574
18241
  message: "kind must be shell or subagent"
17575
18242
  });
17576
18243
  return;
@@ -17586,19 +18253,19 @@ var createTaskHandlers = ({
17586
18253
  signal
17587
18254
  });
17588
18255
  sendResult(
17589
- id,
18256
+ id2,
17590
18257
  subagentTaskInfo(
17591
18258
  params.background === false ? await tasks.wait(task.task_id, { signal }) : task
17592
18259
  )
17593
18260
  );
17594
18261
  } catch (error) {
17595
- sendTaskError2(id, error);
18262
+ sendTaskError2(id2, error);
17596
18263
  }
17597
18264
  return;
17598
18265
  }
17599
18266
  if (params.kind !== "shell") {
17600
- sendError(id, {
17601
- code: RPC_ERROR_CODE16.INVALID_PARAMS,
18267
+ sendError(id2, {
18268
+ code: RPC_ERROR_CODE17.INVALID_PARAMS,
17602
18269
  message: `task kind ${params.kind} is not supported yet.`
17603
18270
  });
17604
18271
  return;
@@ -17606,7 +18273,7 @@ var createTaskHandlers = ({
17606
18273
  const background = params.background !== false;
17607
18274
  const parsed = parseShellSpawnRequest(state, params, { background });
17608
18275
  if ("error" in parsed) {
17609
- sendError(id, parsed.error);
18276
+ sendError(id2, parsed.error);
17610
18277
  return;
17611
18278
  }
17612
18279
  try {
@@ -17633,30 +18300,30 @@ var createTaskHandlers = ({
17633
18300
  const result = background ? toTaskSummary(task, tasks.getProgress(task.task_id)) : toTaskInfo(
17634
18301
  await tasks.wait(task.task_id, { signal: state.activeRunSignal })
17635
18302
  );
17636
- sendResult(id, result);
18303
+ sendResult(id2, result);
17637
18304
  } catch (error) {
17638
- sendTaskError2(id, error);
18305
+ sendTaskError2(id2, error);
17639
18306
  }
17640
18307
  };
17641
- const handleTaskList = async (id, params) => {
18308
+ const handleTaskList = async (id2, params) => {
17642
18309
  const requestedLimit = params?.limit;
17643
18310
  if (requestedLimit !== void 0 && (!Number.isFinite(requestedLimit) || requestedLimit <= 0)) {
17644
- sendError(id, {
17645
- code: RPC_ERROR_CODE16.INVALID_PARAMS,
18311
+ sendError(id2, {
18312
+ code: RPC_ERROR_CODE17.INVALID_PARAMS,
17646
18313
  message: "limit must be a positive number"
17647
18314
  });
17648
18315
  return;
17649
18316
  }
17650
18317
  if (params?.kind !== void 0 && !isTaskKind(params.kind)) {
17651
- sendError(id, {
17652
- code: RPC_ERROR_CODE16.INVALID_PARAMS,
18318
+ sendError(id2, {
18319
+ code: RPC_ERROR_CODE17.INVALID_PARAMS,
17653
18320
  message: "kind must be shell or subagent"
17654
18321
  });
17655
18322
  return;
17656
18323
  }
17657
18324
  if (params?.state !== void 0 && !isTaskState(params.state)) {
17658
- sendError(id, {
17659
- code: RPC_ERROR_CODE16.INVALID_PARAMS,
18325
+ sendError(id2, {
18326
+ code: RPC_ERROR_CODE17.INVALID_PARAMS,
17660
18327
  message: "invalid task state"
17661
18328
  });
17662
18329
  return;
@@ -17667,16 +18334,16 @@ var createTaskHandlers = ({
17667
18334
  (task) => task.kind !== "subagent" || task.subagent?.owner_session_id === state.sessionId
17668
18335
  ).filter((task) => params?.kind ? task.kind === params.kind : true).filter((task) => params?.state ? task.state === params.state : true).slice(0, limit).map((task) => toTaskSummary(task, tasks.getProgress(task.task_id)));
17669
18336
  const result = { tasks: tasksList };
17670
- sendResult(id, result);
18337
+ sendResult(id2, result);
17671
18338
  } catch (error) {
17672
- sendTaskError2(id, error);
18339
+ sendTaskError2(id2, error);
17673
18340
  }
17674
18341
  };
17675
- const handleTaskStatus = async (id, params) => {
18342
+ const handleTaskStatus = async (id2, params) => {
17676
18343
  const taskId = parseTaskId2(params?.task_id);
17677
18344
  if (!taskId) {
17678
- sendError(id, {
17679
- code: RPC_ERROR_CODE16.INVALID_PARAMS,
18345
+ sendError(id2, {
18346
+ code: RPC_ERROR_CODE17.INVALID_PARAMS,
17680
18347
  message: "task_id is required"
17681
18348
  });
17682
18349
  return;
@@ -17694,16 +18361,16 @@ var createTaskHandlers = ({
17694
18361
  task,
17695
18362
  tasks.getProgress(task.task_id)
17696
18363
  );
17697
- sendResult(id, result);
18364
+ sendResult(id2, result);
17698
18365
  } catch (error) {
17699
- sendTaskError2(id, error);
18366
+ sendTaskError2(id2, error);
17700
18367
  }
17701
18368
  };
17702
- const handleTaskWait = async (id, params) => {
18369
+ const handleTaskWait = async (id2, params) => {
17703
18370
  const taskId = parseTaskId2(params?.task_id);
17704
18371
  if (!taskId) {
17705
- sendError(id, {
17706
- code: RPC_ERROR_CODE16.INVALID_PARAMS,
18372
+ sendError(id2, {
18373
+ code: RPC_ERROR_CODE17.INVALID_PARAMS,
17707
18374
  message: "task_id is required"
17708
18375
  });
17709
18376
  return;
@@ -17715,16 +18382,16 @@ var createTaskHandlers = ({
17715
18382
  task,
17716
18383
  tasks.getProgress(task.task_id)
17717
18384
  );
17718
- sendResult(id, result);
18385
+ sendResult(id2, result);
17719
18386
  } catch (error) {
17720
- sendTaskError2(id, error);
18387
+ sendTaskError2(id2, error);
17721
18388
  }
17722
18389
  };
17723
- const handleTaskCancel = async (id, params) => {
18390
+ const handleTaskCancel = async (id2, params) => {
17724
18391
  const taskId = parseTaskId2(params?.task_id);
17725
18392
  if (!taskId) {
17726
- sendError(id, {
17727
- code: RPC_ERROR_CODE16.INVALID_PARAMS,
18393
+ sendError(id2, {
18394
+ code: RPC_ERROR_CODE17.INVALID_PARAMS,
17728
18395
  message: "task_id is required"
17729
18396
  });
17730
18397
  return;
@@ -17738,16 +18405,16 @@ var createTaskHandlers = ({
17738
18405
  task,
17739
18406
  tasks.getProgress(task.task_id)
17740
18407
  );
17741
- sendResult(id, result);
18408
+ sendResult(id2, result);
17742
18409
  } catch (error) {
17743
- sendTaskError2(id, error);
18410
+ sendTaskError2(id2, error);
17744
18411
  }
17745
18412
  };
17746
- const handleTaskResult = async (id, params) => {
18413
+ const handleTaskResult = async (id2, params) => {
17747
18414
  const taskId = parseTaskId2(params?.task_id);
17748
18415
  if (!taskId) {
17749
- sendError(id, {
17750
- code: RPC_ERROR_CODE16.INVALID_PARAMS,
18416
+ sendError(id2, {
18417
+ code: RPC_ERROR_CODE17.INVALID_PARAMS,
17751
18418
  message: "task_id is required"
17752
18419
  });
17753
18420
  return;
@@ -17762,9 +18429,9 @@ var createTaskHandlers = ({
17762
18429
  );
17763
18430
  }
17764
18431
  const result = task.state === "completed" || task.state === "failed" || task.state === "cancelled" ? toTaskInfo(task, tasks.getProgress(task.task_id)) : null;
17765
- sendResult(id, result);
18432
+ sendResult(id2, result);
17766
18433
  } catch (error) {
17767
- sendTaskError2(id, error);
18434
+ sendTaskError2(id2, error);
17768
18435
  }
17769
18436
  };
17770
18437
  return {
@@ -17979,7 +18646,9 @@ var createRuntimeHandlers = ({
17979
18646
  if (!startupOnboardingPromise) return;
17980
18647
  await startupOnboardingPromise;
17981
18648
  };
18649
+ const goalStore = isTuiLocalEnvironment(environment) && sessionStateStore instanceof SessionStateStoreImpl2 ? sessionStateStore.goals : void 0;
17982
18650
  const {
18651
+ handleGoal,
17983
18652
  handleRunStart,
17984
18653
  handleRunSteer,
17985
18654
  handleRunCancel,
@@ -17992,7 +18661,8 @@ var createRuntimeHandlers = ({
17992
18661
  runEventStoreFactory,
17993
18662
  sessionStateStore,
17994
18663
  appendSession,
17995
- beforeRunStart: waitForStartupOnboarding
18664
+ beforeRunStart: waitForStartupOnboarding,
18665
+ goalStore
17996
18666
  });
17997
18667
  const { handleSessionList, handleSessionHistory } = createHistoryHandlers({
17998
18668
  sessionStateStore,
@@ -18059,7 +18729,7 @@ var createRuntimeHandlers = ({
18059
18729
  taskManager: injectedTaskManager,
18060
18730
  outputCache: toolOutputCacheStore ?? void 0
18061
18731
  }) : null;
18062
- const handleInitialize = async (id, params) => {
18732
+ const handleInitialize = async (id2, params) => {
18063
18733
  let resolvedTheme;
18064
18734
  const environment2 = state.effectiveEnvironment;
18065
18735
  if (isTuiLocalEnvironment(environment2)) {
@@ -18095,6 +18765,7 @@ var createRuntimeHandlers = ({
18095
18765
  supports_session_open: true,
18096
18766
  supports_run_cancel: true,
18097
18767
  supports_run_steer: true,
18768
+ supports_goals: Boolean(goalStore),
18098
18769
  supports_run_diagnostics: true,
18099
18770
  supports_session_lifecycle: !!sessionStateStore.updateMetadata,
18100
18771
  supports_shell_exec: processEnabled,
@@ -18123,7 +18794,7 @@ var createRuntimeHandlers = ({
18123
18794
  },
18124
18795
  ...resolvedTheme ? { tui: { theme: resolvedTheme } } : {}
18125
18796
  };
18126
- sendResult(id, result);
18797
+ sendResult(id2, result);
18127
18798
  log2(`initialize from ${params.client?.name ?? "unknown"}`);
18128
18799
  state.lastClientInfo = params.client ?? null;
18129
18800
  state.setUiCapabilities(params.ui_capabilities);
@@ -18135,42 +18806,42 @@ var createRuntimeHandlers = ({
18135
18806
  `ui.context.update cwd=${params.cwd ?? "-"} file=${params.active_file?.path ?? "-"}`
18136
18807
  );
18137
18808
  };
18138
- const handleThemeSet = async (id, params) => {
18809
+ const handleThemeSet = async (id2, params) => {
18139
18810
  if (state.activeRunId) {
18140
- sendError(id, {
18141
- code: RPC_ERROR_CODE17.RUNTIME_BUSY,
18811
+ sendError(id2, {
18812
+ code: RPC_ERROR_CODE18.RUNTIME_BUSY,
18142
18813
  message: "runtime busy"
18143
18814
  });
18144
18815
  return;
18145
18816
  }
18146
18817
  const name2 = params?.name?.trim().toLowerCase();
18147
18818
  if (!name2) {
18148
- sendError(id, {
18149
- code: RPC_ERROR_CODE17.INVALID_PARAMS,
18819
+ sendError(id2, {
18820
+ code: RPC_ERROR_CODE18.INVALID_PARAMS,
18150
18821
  message: "theme name is required"
18151
18822
  });
18152
18823
  return;
18153
18824
  }
18154
18825
  if (!SUPPORTED_TUI_THEMES.has(name2)) {
18155
- sendError(id, {
18156
- code: RPC_ERROR_CODE17.INVALID_PARAMS,
18826
+ sendError(id2, {
18827
+ code: RPC_ERROR_CODE18.INVALID_PARAMS,
18157
18828
  message: `unsupported theme: ${name2}`
18158
18829
  });
18159
18830
  return;
18160
18831
  }
18161
18832
  const workingDir = state.lastUiContext?.cwd ?? state.runtimeWorkingDir ?? process.cwd();
18162
18833
  try {
18163
- const target = await updateEnvironmentTuiTheme(state, workingDir, name2);
18834
+ const target2 = await updateEnvironmentTuiTheme(state, workingDir, name2);
18164
18835
  const result = {
18165
18836
  name: name2,
18166
- scope: target.scope,
18167
- path: target.path
18837
+ scope: target2.scope,
18838
+ path: target2.path
18168
18839
  };
18169
- sendResult(id, result);
18170
- log2(`theme.set ${name2} scope=${target.scope} path=${target.path}`);
18840
+ sendResult(id2, result);
18841
+ log2(`theme.set ${name2} scope=${target2.scope} path=${target2.path}`);
18171
18842
  } catch (error) {
18172
- sendError(id, {
18173
- code: RPC_ERROR_CODE17.RUNTIME_INTERNAL,
18843
+ sendError(id2, {
18844
+ code: RPC_ERROR_CODE18.RUNTIME_INTERNAL,
18174
18845
  message: String(error)
18175
18846
  });
18176
18847
  }
@@ -18191,7 +18862,7 @@ var createRuntimeHandlers = ({
18191
18862
  const skillsEnabled = state.effectiveEnvironment.context.skills === "from-config";
18192
18863
  const themeSetEnabled = isTuiLocalEnvironment(state.effectiveEnvironment) && state.effectiveEnvironment.config.source !== "disabled";
18193
18864
  const rejectDisabled = (message) => sendError(req.id, {
18194
- code: RPC_ERROR_CODE17.INVALID_PARAMS,
18865
+ code: RPC_ERROR_CODE18.INVALID_PARAMS,
18195
18866
  message
18196
18867
  });
18197
18868
  switch (req.method) {
@@ -18202,6 +18873,13 @@ var createRuntimeHandlers = ({
18202
18873
  case "attachment.upload.finish":
18203
18874
  case "attachment.upload.cancel":
18204
18875
  return handleAttachmentUpload(state, req.id, req.method, req.params);
18876
+ case "goal.get":
18877
+ case "goal.set":
18878
+ case "goal.pause":
18879
+ case "goal.resume":
18880
+ case "goal.clear":
18881
+ case "goal.continue":
18882
+ return handleGoal(req.id, req.method, req.params);
18205
18883
  case "run.start":
18206
18884
  return handleRunStart(req.id, req.params);
18207
18885
  case "run.steer":
@@ -18389,7 +19067,7 @@ var createRuntimeHandlers = ({
18389
19067
  return handleThemeSet(req.id, req.params);
18390
19068
  default:
18391
19069
  return sendError(req.id, {
18392
- code: RPC_ERROR_CODE17.METHOD_NOT_FOUND,
19070
+ code: RPC_ERROR_CODE18.METHOD_NOT_FOUND,
18393
19071
  message: "method not found"
18394
19072
  });
18395
19073
  }
@@ -18408,11 +19086,11 @@ var createRuntimeHandlers = ({
18408
19086
  log2("invalid rpc message");
18409
19087
  return;
18410
19088
  }
18411
- const id = typeof msg.id === "string" ? msg.id : void 0;
19089
+ const id2 = typeof msg.id === "string" ? msg.id : void 0;
18412
19090
  if (msg.jsonrpc !== "2.0" || "method" in msg && typeof msg.method !== "string") {
18413
- if (id !== void 0) {
18414
- sendError(id, {
18415
- code: RPC_ERROR_CODE17.INVALID_REQUEST,
19091
+ if (id2 !== void 0) {
19092
+ sendError(id2, {
19093
+ code: RPC_ERROR_CODE18.INVALID_REQUEST,
18416
19094
  message: "invalid request"
18417
19095
  });
18418
19096
  } else {
@@ -18421,29 +19099,29 @@ var createRuntimeHandlers = ({
18421
19099
  return;
18422
19100
  }
18423
19101
  if (typeof msg.method === "string") {
18424
- if ("id" in msg && id === void 0) {
19102
+ if ("id" in msg && id2 === void 0) {
18425
19103
  log2("invalid rpc request id");
18426
19104
  return;
18427
19105
  }
18428
19106
  const invalid = validateRequestParams(msg.method, msg.params);
18429
19107
  if (invalid) {
18430
- if (id !== void 0)
18431
- sendError(id, {
18432
- code: RPC_ERROR_CODE17.INVALID_PARAMS,
19108
+ if (id2 !== void 0)
19109
+ sendError(id2, {
19110
+ code: RPC_ERROR_CODE18.INVALID_PARAMS,
18433
19111
  message: invalid
18434
19112
  });
18435
19113
  else log2(`invalid rpc notification: ${msg.method}`);
18436
19114
  return;
18437
19115
  }
18438
- if (id !== void 0) {
18439
- void withRpcResponseContext(id, async () => {
19116
+ if (id2 !== void 0) {
19117
+ void withRpcResponseContext(id2, async () => {
18440
19118
  try {
18441
19119
  await handleRequest(msg);
18442
19120
  } catch {
18443
- if (!hasRpcResponse(id)) {
19121
+ if (!hasRpcResponse(id2)) {
18444
19122
  try {
18445
- sendError(id, {
18446
- code: RPC_ERROR_CODE17.RUNTIME_INTERNAL,
19123
+ sendError(id2, {
19124
+ code: RPC_ERROR_CODE18.RUNTIME_INTERNAL,
18447
19125
  message: "internal runtime error"
18448
19126
  });
18449
19127
  } catch {
@@ -18464,11 +19142,11 @@ var createRuntimeHandlers = ({
18464
19142
  }
18465
19143
  return;
18466
19144
  }
18467
- if (id !== void 0 && ("result" in msg || "error" in msg)) {
19145
+ if (id2 !== void 0 && ("result" in msg || "error" in msg)) {
18468
19146
  handleResponse(msg);
18469
- } else if (id !== void 0) {
18470
- sendError(id, {
18471
- code: RPC_ERROR_CODE17.INVALID_REQUEST,
19147
+ } else if (id2 !== void 0) {
19148
+ sendError(id2, {
19149
+ code: RPC_ERROR_CODE18.INVALID_REQUEST,
18472
19150
  message: "invalid request"
18473
19151
  });
18474
19152
  } else {
@@ -18541,10 +19219,10 @@ var prepareProcess = (input, options, channel) => {
18541
19219
  }
18542
19220
  }
18543
19221
  };
18544
- const send2 = (id, method, params) => {
19222
+ const send2 = (id2, method, params) => {
18545
19223
  if (!child?.stdin?.writable || closed) return;
18546
19224
  child.stdin.write(
18547
- `${JSON.stringify({ jsonrpc: "2.0", id, method, params })}
19225
+ `${JSON.stringify({ jsonrpc: "2.0", id: id2, method, params })}
18548
19226
  `
18549
19227
  );
18550
19228
  };