zcode-app-cli 3.9.1-16 → 3.9.2-16

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.
@@ -22511,7 +22511,7 @@ var require_view = __commonJS({
22511
22511
  var dirname4 = path.dirname;
22512
22512
  var basename2 = path.basename;
22513
22513
  var extname = path.extname;
22514
- var join7 = path.join;
22514
+ var join6 = path.join;
22515
22515
  var resolve3 = path.resolve;
22516
22516
  module.exports = View;
22517
22517
  function View(name, options) {
@@ -22573,12 +22573,12 @@ var require_view = __commonJS({
22573
22573
  };
22574
22574
  View.prototype.resolve = function resolve4(dir, file2) {
22575
22575
  var ext = this.ext;
22576
- var path2 = join7(dir, file2);
22576
+ var path2 = join6(dir, file2);
22577
22577
  var stat = tryStat(path2);
22578
22578
  if (stat && stat.isFile()) {
22579
22579
  return path2;
22580
22580
  }
22581
- path2 = join7(dir, basename2(file2, ext), "index" + ext);
22581
+ path2 = join6(dir, basename2(file2, ext), "index" + ext);
22582
22582
  stat = tryStat(path2);
22583
22583
  if (stat && stat.isFile()) {
22584
22584
  return path2;
@@ -26283,7 +26283,7 @@ var require_send = __commonJS({
26283
26283
  var Stream = __require("stream");
26284
26284
  var util2 = __require("util");
26285
26285
  var extname = path.extname;
26286
- var join7 = path.join;
26286
+ var join6 = path.join;
26287
26287
  var normalize = path.normalize;
26288
26288
  var resolve3 = path.resolve;
26289
26289
  var sep = path.sep;
@@ -26455,7 +26455,7 @@ var require_send = __commonJS({
26455
26455
  return res;
26456
26456
  }
26457
26457
  parts = path2.split(sep);
26458
- path2 = normalize(join7(root, path2));
26458
+ path2 = normalize(join6(root, path2));
26459
26459
  } else {
26460
26460
  if (UP_PATH_REGEXP.test(path2)) {
26461
26461
  debug('malicious path "%s"', path2);
@@ -26588,7 +26588,7 @@ var require_send = __commonJS({
26588
26588
  if (err) return self.onStatError(err);
26589
26589
  return self.error(404);
26590
26590
  }
26591
- var p = join7(path2, self._index[i]);
26591
+ var p = join6(path2, self._index[i]);
26592
26592
  debug('stat "%s"', p);
26593
26593
  fs.stat(p, function(err2, stat) {
26594
26594
  if (err2) return next(err2);
@@ -27479,9 +27479,6 @@ import { dirname, join } from "node:path";
27479
27479
  import { AsyncLocalStorage as AsyncLocalStorage4 } from "node:async_hooks";
27480
27480
  import { randomUUID as randomUUID2 } from "node:crypto";
27481
27481
  import { randomBytes } from "node:crypto";
27482
- import { chmodSync as chmodSync2, mkdtempSync, rmSync as rmSync2, writeFileSync as writeFileSync2 } from "node:fs";
27483
- import { tmpdir as tmpdir2 } from "node:os";
27484
- import { join as join3 } from "node:path";
27485
27482
  import { createHash as createHash3 } from "node:crypto";
27486
27483
  import { createRequire } from "node:module";
27487
27484
  import { join as join2 } from "node:path";
@@ -27493,10 +27490,10 @@ import { Http2ServerRequest as Http2ServerRequest2, constants as h2constants } f
27493
27490
  import { Http2ServerRequest } from "http2";
27494
27491
  import { Readable } from "stream";
27495
27492
  import crypto2 from "crypto";
27496
- import { appendFileSync, existsSync, writeFileSync as writeFileSync3 } from "node:fs";
27497
- import { dirname as dirname2, isAbsolute as isAbsolute2, join as join4 } from "node:path";
27498
- import { join as join5 } from "node:path";
27499
- import { dirname as dirname3, join as join6, resolve } from "node:path";
27493
+ import { appendFileSync, existsSync, writeFileSync as writeFileSync2 } from "node:fs";
27494
+ import { dirname as dirname2, isAbsolute as isAbsolute2, join as join3 } from "node:path";
27495
+ import { join as join4 } from "node:path";
27496
+ import { dirname as dirname3, join as join5, resolve } from "node:path";
27500
27497
  var __create2 = Object.create;
27501
27498
  var __defProp2 = Object.defineProperty;
27502
27499
  var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
@@ -57977,13 +57974,7 @@ function isBrokerUnavailableException(exc) {
57977
57974
  return exc instanceof PermissionBrokerError && exc.code === BROKER_UNAVAILABLE_CODE;
57978
57975
  }
57979
57976
  function shouldPropagateToWrapper(exc) {
57980
- return isBrokerUnavailableException(exc) || isMacTccPermissionRefusal(exc);
57981
- }
57982
- function isPermissionRefusalException(exc) {
57983
- return exc instanceof PermissionBrokerError && exc.permissionError === true && exc.code === "permission_denied" && !isBrokerUnavailableException(exc);
57984
- }
57985
- function isMacTccPermissionRefusal(exc, platform = process.platform) {
57986
- return platform === "darwin" && isPermissionRefusalException(exc);
57977
+ return isBrokerUnavailableException(exc);
57987
57978
  }
57988
57979
  var MAX_FRAME_BYTES = 64 * 1024 * 1024;
57989
57980
  var MAX_HOLD_DURATION = 30;
@@ -59849,27 +59840,16 @@ var FrameRegistry = class {
59849
59840
  }
59850
59841
  /**
59851
59842
  * Resolve model-supplied pixel authority. Retained descriptors remain
59852
- * available to internal diagnostics, but once a newer actionable raster is
59853
- * issued an older frame can no longer actuate the GUI.
59843
+ * actionable until TTL/LRU/actionability checks fail them closed.
59854
59844
  */
59855
59845
  resolveForAction(frame_id) {
59856
- const frame = this.resolve(frame_id);
59857
- if (this.latestActionableFrameId !== frame_id) {
59858
- throw new FrameRegistryError(
59859
- "superseded_frame",
59860
- this.recoveryMessage(frame_id, "superseded_frame"),
59861
- frame_id
59862
- );
59863
- }
59864
- return frame;
59846
+ return this.resolve(frame_id);
59865
59847
  }
59866
59848
  /**
59867
59849
  * Bind model-visible pixels to this transport's current raster authority.
59868
59850
  *
59869
- * 根因:部分多模态网关能交付 image-first 的截图,却会丢弃同一 tool_result
59870
- * 中紧随图片的 image_ref 文本。frame_id 是 transport 内部权限,不应要求模型
59871
- * 看见并转抄。这里仍复用 resolveForAction 的 TTL/latest 检查;没有权威帧时
59872
- * fail-closed,不会跨 session 或猜测其他帧。
59851
+ * frame_id 是 transport 内部权限,默认坐标动作不要求模型转抄。这里仍复用
59852
+ * resolveForAction 的 TTL/actionability 检查;没有权威帧时 fail-closed。
59873
59853
  */
59874
59854
  resolveLatestForAction() {
59875
59855
  if (this.latestActionableFrameId === null) {
@@ -59883,27 +59863,6 @@ var FrameRegistry = class {
59883
59863
  get(frame_id) {
59884
59864
  return this.frames.get(frame_id) ?? null;
59885
59865
  }
59886
- /**
59887
- * 按新→旧返回仍可参与像素投影的保留帧(未过期、actionable、未被 tombstone)。
59888
- *
59889
- * Bug 根因(zoom 后坐标必越界,轨迹 sess_51043d32):zoom 裁剪图注册为
59890
- * latest 权威帧后,模型仍常按祖先全屏帧的坐标系出坐标/region,直接按裁剪图
59891
- * delivered 尺寸拒绝会让动作失败并迫使模型重截图。回退投影需要按新→旧遍历
59892
- * 保留帧,找到能完整容纳该坐标/区域的祖先帧;zoom 裁剪的正是祖先帧的同一份
59893
- * 字节,用祖先帧几何投影不引入新的过期风险。只读查询,不改变
59894
- * resolveForAction 的 latest-only 强校验语义(显式 frame_id 路径不受影响)。
59895
- */
59896
- retainedActionableFramesNewestFirst() {
59897
- const now = this.now();
59898
- const retained = [];
59899
- for (const frame of this.frames.values()) {
59900
- if (!frame.actionable) continue;
59901
- if (now > frame.expires_at_ms) continue;
59902
- retained.push(frame);
59903
- }
59904
- retained.reverse();
59905
- return retained;
59906
- }
59907
59866
  tombstoneReason(frame_id) {
59908
59867
  return this.tombstones.get(frame_id) ?? null;
59909
59868
  }
@@ -59956,10 +59915,8 @@ var AccessibilitySession = class {
59956
59915
  observationRepeatCount = 0;
59957
59916
  /** App/window identities that already received the one-shot empty AX-tree warmup. */
59958
59917
  emptyTreeWarmups = /* @__PURE__ */ new Set();
59959
- /** 动作进入原生调用后,旧观察不再具有执行权限,即使 AX 最终返回 error。 */
59918
+ /** 动作进入原生调用后,本次引用的旧观察不再具有执行权限。 */
59960
59919
  supersededStateIds = /* @__PURE__ */ new Set();
59961
- /** post-observe 失败的 app/window 在 full observation 之前保持写锁定。 */
59962
- refreshRequiredScopes = [];
59963
59920
  constructor(maxStates = DEFAULT_MAX_STATES) {
59964
59921
  if (!Number.isInteger(maxStates) || maxStates < 1) {
59965
59922
  throw new Error(`AccessibilitySession maxStates must be a positive integer (got ${maxStates})`);
@@ -60014,11 +59971,6 @@ var AccessibilitySession = class {
60014
59971
  this.entries.delete(state.state_id);
60015
59972
  }
60016
59973
  this.entries.set(state.state_id, state);
60017
- this.refreshRequiredScopes = this.refreshRequiredScopes.filter(
60018
- // 旧 token 的废弃是 window 级;full observation 的解锁是 app 级。动作可能
60019
- // 合法关闭旧窗口,所以不能要求已经消失的 window_id 再次出现才能解锁。
60020
- (scope) => !stateMatchesMutationApp(state, scope)
60021
- );
60022
59974
  while (this.entries.size > this.maxStates) {
60023
59975
  const oldest = this.entries.keys().next().value;
60024
59976
  if (oldest === void 0) break;
@@ -60046,8 +59998,7 @@ var AccessibilitySession = class {
60046
59998
  }
60047
59999
  /** 在原生调用前冻结基线,不改变任何可执行状态。 */
60048
60000
  beginMutation(appRef2, preStateId) {
60049
- const explicit = preStateId ? this.entries.get(preStateId) ?? null : null;
60050
- const preActionState = explicit ?? this.latestStateForAppRef(appRef2);
60001
+ const preActionState = preStateId === null ? null : preStateId === void 0 ? this.latestStateForAppRef(appRef2) : this.entries.get(preStateId) ?? null;
60051
60002
  const scope = mutationScopeFrom(appRef2, preActionState);
60052
60003
  if (!mutationScopeHasAppIdentity(scope)) {
60053
60004
  throw new Error(
@@ -60060,23 +60011,20 @@ var AccessibilitySession = class {
60060
60011
  };
60061
60012
  }
60062
60013
  /**
60063
- * 原生调用已经开始:不能再依据 AX 返回值猜测副作用是否发生。废弃同一 scope 的
60064
- * 所有旧状态,并在 full observation 到来前阻止继续写入。
60014
+ * 原生调用已经开始:不能再依据 AX 返回值猜测副作用是否发生。只废弃本次动作
60015
+ * 实际引用的 pre_state_id;同 app/window 的其它已观察状态不被 scope-wide 锁死。
60065
60016
  */
60066
60017
  markMutationDispatched(ticket) {
60067
- for (const [stateId, state] of this.entries) {
60068
- if (stateMatchesMutationScope(state, ticket.scope)) {
60069
- this.supersededStateIds.add(stateId);
60070
- }
60071
- }
60072
- if (!this.refreshRequiredScopes.some((scope) => sameMutationScope(scope, ticket.scope))) {
60073
- this.refreshRequiredScopes.push(ticket.scope);
60074
- }
60018
+ this.consumeReferencedState(ticket);
60019
+ }
60020
+ /** 废弃动作明确引用、但已被 Helper 证明失效的唯一 state。 */
60021
+ consumeReferencedState(ticket) {
60022
+ const stateId = ticket.preActionState?.state_id;
60023
+ if (stateId && this.entries.has(stateId)) this.supersededStateIds.add(stateId);
60075
60024
  }
60076
60025
  requiresRefresh(appRef2) {
60077
- const probe = mutationScopeFrom(appRef2, null);
60078
- if (!mutationScopeHasAppIdentity(probe)) return false;
60079
- return this.refreshRequiredScopes.some((scope) => mutationScopesOverlap(scope, probe));
60026
+ void appRef2;
60027
+ return false;
60080
60028
  }
60081
60029
  /**
60082
60030
  * The most-recently-used state_id (last key — `Map` iteration is touch
@@ -60134,22 +60082,6 @@ var AccessibilitySession = class {
60134
60082
  }
60135
60083
  return matches[0] ?? null;
60136
60084
  }
60137
- /**
60138
- * Decide whether an implicit (`strategy=auto`) click should keep using AX,
60139
- * or use the foreground-gated event path for a known AX shell.
60140
- *
60141
- * Post-action digest equality is diagnostic only: it cannot prove that an
60142
- * AXPress had no external, focus-only, or otherwise unobserved effect, so it
60143
- * must never change the route of this or a later element action.
60144
- */
60145
- pointerFallbackDecision(appRef2) {
60146
- const state = this.latestStateForAppRef(appRef2);
60147
- if (!state) return { mode: "a11y" };
60148
- if (!state.elements.some(isActionableElement)) {
60149
- return { mode: "event", reason: "low_ax_quality" };
60150
- }
60151
- return { mode: "a11y" };
60152
- }
60153
60085
  selectDisplay(displayId) {
60154
60086
  if (!Number.isInteger(displayId)) {
60155
60087
  throw new Error(`display id must be an integer (got ${displayId})`);
@@ -60199,7 +60131,6 @@ var AccessibilitySession = class {
60199
60131
  clear() {
60200
60132
  this.entries.clear();
60201
60133
  this.supersededStateIds.clear();
60202
- this.refreshRequiredScopes = [];
60203
60134
  this.counter = 0;
60204
60135
  this.frameRegistry.clear();
60205
60136
  this.selectedDisplayId = null;
@@ -60220,38 +60151,9 @@ function mutationScopeFrom(appRef2, fallback) {
60220
60151
  window_id: typeof ref.window_id === "number" ? ref.window_id : fallback?.window.window_id ?? null
60221
60152
  };
60222
60153
  }
60223
- function stateMatchesMutationScope(state, scope) {
60224
- if (scope.pid !== null && state.app.pid !== scope.pid) return false;
60225
- if (scope.bundle_id && state.app.bundle_id !== scope.bundle_id) return false;
60226
- if (scope.name && state.app.name !== scope.name) return false;
60227
- if (scope.window_id !== null && state.window.window_id !== scope.window_id) return false;
60228
- return scope.pid !== null || Boolean(scope.bundle_id || scope.name);
60229
- }
60230
60154
  function mutationScopeHasAppIdentity(scope) {
60231
60155
  return scope.pid !== null || Boolean(scope.bundle_id || scope.name);
60232
60156
  }
60233
- function stateMatchesMutationApp(state, scope) {
60234
- if (!mutationScopeHasAppIdentity(scope)) return false;
60235
- if (scope.pid !== null && state.app.pid !== scope.pid) return false;
60236
- if (scope.bundle_id && state.app.bundle_id !== scope.bundle_id) return false;
60237
- if (scope.name && state.app.name !== scope.name) return false;
60238
- return true;
60239
- }
60240
- function sameMutationScope(left, right) {
60241
- return left.pid === right.pid && left.bundle_id === right.bundle_id && left.name === right.name && left.window_id === right.window_id;
60242
- }
60243
- function mutationScopesOverlap(left, right) {
60244
- if (left.pid !== null && right.pid !== null && left.pid !== right.pid) return false;
60245
- if (left.bundle_id && right.bundle_id && left.bundle_id !== right.bundle_id) return false;
60246
- if (left.name && right.name && left.name !== right.name) return false;
60247
- if (left.window_id !== null && right.window_id !== null && left.window_id !== right.window_id) {
60248
- return false;
60249
- }
60250
- return true;
60251
- }
60252
- function isActionableElement(element) {
60253
- return element.pressable || element.editable || element.has_menu || element.actions.length > 0;
60254
- }
60255
60157
  function sameApp(cached2, observed) {
60256
60158
  if (typeof observed.pid === "number") return cached2.pid === observed.pid;
60257
60159
  if (typeof observed.bundle_id === "string" && observed.bundle_id) {
@@ -60410,6 +60312,44 @@ function loadSharp() {
60410
60312
  }
60411
60313
  return sharpPromise;
60412
60314
  }
60315
+ function asSurfaceKind(value) {
60316
+ return value === "window" || value === "attached_dialog" || value === "open_panel" || value === "save_panel" || value === "popover" ? value : null;
60317
+ }
60318
+ function parseAppFrameSurfaceSet(value) {
60319
+ if (value === void 0 || value === null) return null;
60320
+ if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
60321
+ const record2 = value;
60322
+ if (!Number.isSafeInteger(record2.presentation_window_id) || record2.presentation_window_id <= 0 || typeof record2.before_fingerprint !== "string" || record2.before_fingerprint.length === 0 || typeof record2.after_fingerprint !== "string" || record2.after_fingerprint.length === 0 || record2.order !== "front_to_back" || !Array.isArray(record2.surfaces) || record2.surfaces.length < 1 || record2.surfaces.length > 64) {
60323
+ return void 0;
60324
+ }
60325
+ const surfaces = record2.surfaces.map((entry) => {
60326
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) return null;
60327
+ const surface = entry;
60328
+ const kind = asSurfaceKind(surface.surface_kind);
60329
+ const bounds = surface.bounds;
60330
+ if (!Number.isSafeInteger(surface.actual_window_id) || surface.actual_window_id <= 0 || !Number.isSafeInteger(surface.presentation_window_id) || surface.presentation_window_id <= 0 || !kind || surface.relation !== "presentation_root" && surface.relation !== "ax_descendant" || !Number.isSafeInteger(surface.owner_pid) || surface.owner_pid <= 0 || typeof surface.owner_bundle_id !== "string" || surface.owner_bundle_id.length === 0 || !Number.isSafeInteger(surface.layer) || !Array.isArray(bounds) || bounds.length !== 4 || !bounds.every(Number.isFinite)) {
60331
+ return null;
60332
+ }
60333
+ return {
60334
+ actual_window_id: surface.actual_window_id,
60335
+ presentation_window_id: surface.presentation_window_id,
60336
+ surface_kind: kind,
60337
+ relation: surface.relation,
60338
+ owner_pid: surface.owner_pid,
60339
+ owner_bundle_id: surface.owner_bundle_id,
60340
+ layer: surface.layer,
60341
+ bounds
60342
+ };
60343
+ });
60344
+ if (surfaces.some((surface) => surface === null)) return void 0;
60345
+ return {
60346
+ presentation_window_id: record2.presentation_window_id,
60347
+ before_fingerprint: record2.before_fingerprint,
60348
+ after_fingerprint: record2.after_fingerprint,
60349
+ order: "front_to_back",
60350
+ surfaces
60351
+ };
60352
+ }
60413
60353
  function asBounds(value, where) {
60414
60354
  if (!Array.isArray(value) || value.length !== 4) {
60415
60355
  throw new Error(`${where} must be a 4-number bounds array; got ${JSON.stringify(value)}`);
@@ -60438,6 +60378,8 @@ function asElements(raw) {
60438
60378
  editable: typeof el.editable === "boolean" ? el.editable : false,
60439
60379
  actions,
60440
60380
  focused: typeof el.focused === "boolean" ? el.focused : false,
60381
+ ...typeof el.selected === "boolean" ? { selected: el.selected } : {},
60382
+ default_action: typeof el.default_action === "boolean" ? el.default_action : false,
60441
60383
  pressable: typeof el.pressable === "boolean" ? el.pressable : actions.includes("AXPress"),
60442
60384
  has_menu: typeof el.has_menu === "boolean" ? el.has_menu : actions.includes("AXShowMenu"),
60443
60385
  native: typeof el.native === "string" ? el.native : "",
@@ -60450,6 +60392,9 @@ function asElements(raw) {
60450
60392
  };
60451
60393
  });
60452
60394
  }
60395
+ function asSurfaceKind2(value) {
60396
+ return value === "window" || value === "attached_dialog" || value === "open_panel" || value === "save_panel" || value === "popover" ? value : null;
60397
+ }
60453
60398
  async function probeScreenshotSize(screenshot) {
60454
60399
  if (!screenshot) return null;
60455
60400
  const data = screenshot.data;
@@ -60477,7 +60422,11 @@ async function issueCaptureFrame(raw, app, window2, session) {
60477
60422
  const py = geometryVerified ? pointer.y : 0;
60478
60423
  const pw = geometryVerified ? pointer.width : 0;
60479
60424
  const ph = geometryVerified ? pointer.height : 0;
60480
- const nonActionableReason = screenshotBlank ? "screenshot_blank" : geometryVerified ? null : "capture_geometry_unverified";
60425
+ const parsedCaptureSurfaces = parseAppFrameSurfaceSet(raw.capture_surfaces);
60426
+ const captureSurfaces = parsedCaptureSurfaces ?? null;
60427
+ const malformedCaptureSurfaces = raw.capture_surfaces !== void 0 && raw.capture_surfaces !== null && parsedCaptureSurfaces === void 0;
60428
+ const surfaceStatus = raw.capture_surfaces_status;
60429
+ const nonActionableReason = screenshotBlank ? "screenshot_blank" : surfaceStatus === "capture_surfaces_changed" ? "capture_surfaces_changed" : surfaceStatus === "capture_surfaces_unavailable" ? "capture_surfaces_unavailable" : malformedCaptureSurfaces ? "capture_surfaces_unavailable" : raw.capture_surfaces && raw.capture_surfaces.before_fingerprint !== raw.capture_surfaces.after_fingerprint ? "capture_surfaces_changed" : geometryVerified ? null : "capture_geometry_unverified";
60481
60430
  const frame = session.issueFrame({
60482
60431
  delivered: {
60483
60432
  width: rasterSize.width,
@@ -60512,7 +60461,8 @@ async function issueCaptureFrame(raw, app, window2, session) {
60512
60461
  topology_fingerprint: raw.display?.topology_fingerprint ?? "unverified",
60513
60462
  origin: { x: raw.pointer?.x ?? px, y: raw.pointer?.y ?? py }
60514
60463
  },
60515
- actionable: !screenshotBlank && geometryVerified,
60464
+ capture_surfaces: captureSurfaces,
60465
+ actionable: nonActionableReason === null,
60516
60466
  non_actionable_reason: nonActionableReason
60517
60467
  });
60518
60468
  return frame.image_ref;
@@ -60535,7 +60485,11 @@ async function ingestCaptureAppResult(raw, options) {
60535
60485
  window_id: typeof raw.window.window_id === "number" ? raw.window.window_id : null,
60536
60486
  window_id_fallback: raw.window.window_id_fallback === true || void 0,
60537
60487
  empty_capture_reason: typeof raw.window.empty_capture_reason === "string" && raw.window.empty_capture_reason.length > 0 ? raw.window.empty_capture_reason : void 0,
60538
- note: raw.window.window_id_fallback === true && typeof raw.window.note === "string" ? raw.window.note : void 0
60488
+ note: raw.window.window_id_fallback === true && typeof raw.window.note === "string" ? raw.window.note : void 0,
60489
+ actual_window_id: typeof raw.window.actual_window_id === "number" ? raw.window.actual_window_id : typeof raw.window.window_id === "number" ? raw.window.window_id : null,
60490
+ presentation_window_id: typeof raw.window.presentation_window_id === "number" ? raw.window.presentation_window_id : typeof raw.window.window_id === "number" ? raw.window.window_id : null,
60491
+ surface_kind: asSurfaceKind2(raw.window.surface_kind) ?? "window",
60492
+ surface_lifecycle: raw.window.surface_lifecycle === "replaced" || raw.window.surface_lifecycle === "closed" ? raw.window.surface_lifecycle : "stable"
60539
60493
  };
60540
60494
  const elements = asElements(raw.elements);
60541
60495
  const screenshotBlank = raw.screenshot_blank === true;
@@ -60551,7 +60505,9 @@ async function ingestCaptureAppResult(raw, options) {
60551
60505
  screenshot_blank: screenshotBlank || void 0
60552
60506
  };
60553
60507
  const imageRef = await issueCaptureFrame(raw, app, window2, session);
60554
- if (imageRef) state.image_ref = imageRef;
60508
+ if (imageRef) {
60509
+ state.image_ref = imageRef;
60510
+ }
60555
60511
  session.remember(state);
60556
60512
  return state;
60557
60513
  }
@@ -60587,6 +60543,8 @@ function elementRow(index, el, detail) {
60587
60543
  flag(el.editable, "editable"),
60588
60544
  flag(el.has_menu, "has_menu"),
60589
60545
  flag(el.focused, "focused"),
60546
+ flag(el.selected === true, "selected"),
60547
+ flag(el.default_action === true, "default_action"),
60590
60548
  flag(!el.enabled, "disabled")
60591
60549
  ].filter(Boolean).join(" ");
60592
60550
  const synthesized = el.title ? "" : synthesizeLabel(el, index);
@@ -60627,6 +60585,20 @@ function formatAppStateTree(state, detail = "compact") {
60627
60585
  const windowId = typeof win.window_id === "number" ? ` window_id=${win.window_id}` : "";
60628
60586
  const fallbackNote = win.window_id_fallback ? `[window_id_fallback] ${win.note ?? "The requested window could not be resolved; a different live window was returned. Call list_windows before acting."}` : "";
60629
60587
  const emptyCaptureNote = win.empty_capture_reason ? `[${win.empty_capture_reason}] ${EMPTY_CAPTURE_GUIDANCE[win.empty_capture_reason] ?? "This app exposed no window tree. Retrying the same read is unlikely to help; re-resolve the app with list_windows first."}` : "";
60588
+ const surfaceLine = win.surface_kind ? `surface: kind=${win.surface_kind} actual_window_id=${win.actual_window_id ?? win.window_id ?? "unknown"} presentation_window_id=${win.presentation_window_id ?? win.window_id ?? "unknown"} lifecycle=${win.surface_lifecycle ?? "stable"}` : "";
60589
+ const filePanelSummary = (() => {
60590
+ if (win.surface_kind !== "open_panel" && win.surface_kind !== "save_panel") {
60591
+ return "";
60592
+ }
60593
+ const selected = state.elements.filter((element) => element.selected === true).map((element) => element.title ?? element.value).filter((value) => typeof value === "string" && value.length > 0);
60594
+ const defaultAction = state.elements.find(
60595
+ (element) => element.default_action === true
60596
+ );
60597
+ return [
60598
+ `file_panel: selected=[${selected.join(",")}] default_action=${defaultAction?.title ?? "unknown"} enabled=${defaultAction?.enabled ?? false}`,
60599
+ "file_panel_guidance: For an exact path use Cmd+Shift+G, observe the attached surface again, type the full path, then confirm once."
60600
+ ].join("\n");
60601
+ })();
60630
60602
  const maxElements = 200;
60631
60603
  let entries = state.elements.map((el, index) => ({ el, index }));
60632
60604
  let truncatedCount = 0;
@@ -60647,6 +60619,8 @@ function formatAppStateTree(state, detail = "compact") {
60647
60619
  `app: ${appLine}`,
60648
60620
  GLOBAL_SCREEN_COORDINATE_CONTRACT,
60649
60621
  `window:${title}${windowId} bounds=[${wx},${wy},${ww},${wh}] screen_rect=[${screenRect.join(",")}]`,
60622
+ surfaceLine,
60623
+ filePanelSummary,
60650
60624
  fallbackNote,
60651
60625
  emptyCaptureNote,
60652
60626
  `elements (${entries.length}${truncatedCount > 0 ? ` of ${state.elements.length}` : ""}):`,
@@ -60660,6 +60634,8 @@ function elementPriority(el, windowBounds) {
60660
60634
  const container = /group|split|scroll|layout|container|pane|unknown/.test(kind);
60661
60635
  const leafControl = /button|check|radio|switch|link|menuitem|tab|textfield|textarea|slider/.test(kind);
60662
60636
  if (el.focused) score += 220;
60637
+ if (el.selected) score += 240;
60638
+ if (el.default_action) score += 240;
60663
60639
  if (el.pressable && el.enabled) score += 200;
60664
60640
  if (leafControl) score += 100;
60665
60641
  if (el.title) score += 60;
@@ -60696,72 +60672,33 @@ function projectFramePixelToPointer(frame, pixel) {
60696
60672
  y: frame.pointer.y + sourceY * (frame.pointer.height / frame.source.height)
60697
60673
  };
60698
60674
  }
60675
+ var implicitFrameBindings = /* @__PURE__ */ new WeakSet();
60676
+ function frameBindingKind(target) {
60677
+ if (target && typeof target === "object" && implicitFrameBindings.has(target)) {
60678
+ return "implicit";
60679
+ }
60680
+ const frameId = target?.frame_id;
60681
+ return typeof frameId === "string" && frameId.length > 0 ? "explicit" : "implicit";
60682
+ }
60699
60683
  function bindFramePixelTarget(target, context) {
60684
+ const bindingKind = frameBindingKind(target);
60700
60685
  const explicitFrameId = target.frame_id;
60701
60686
  const frame = typeof explicitFrameId === "string" && explicitFrameId.length > 0 ? context.frame_registry.resolveForAction(explicitFrameId) : context.frame_registry.resolveLatestForAction();
60702
- return {
60687
+ const bound = {
60703
60688
  type: "coordinate",
60704
60689
  frame_id: frame.frame_id,
60705
60690
  x: target.x,
60706
60691
  y: target.y
60707
60692
  };
60708
- }
60709
- function pixelInsideFrame(frame, x, y) {
60710
- return Number.isInteger(x) && Number.isInteger(y) && x >= 0 && y >= 0 && x < frame.delivered.width && y < frame.delivered.height;
60711
- }
60712
- function regionInsideFrame(frame, region) {
60713
- const [x0, y0, x1, y1] = region;
60714
- return x0 >= 0 && y0 >= 0 && x1 <= frame.delivered.width && y1 <= frame.delivered.height;
60715
- }
60716
- function findFallbackFrame(registry2, latest, options) {
60717
- for (const candidate of registry2.retainedActionableFramesNewestFirst()) {
60718
- if (candidate.frame_id === latest.frame_id) continue;
60719
- if (candidate.display.topology_fingerprint !== latest.display.topology_fingerprint) {
60720
- continue;
60721
- }
60722
- if (options.requireRetainedData && !candidate.delivered.data) continue;
60723
- if (options.pixel && !pixelInsideFrame(candidate, options.pixel.x, options.pixel.y)) continue;
60724
- if (options.region && !regionInsideFrame(candidate, options.region)) continue;
60725
- return candidate;
60726
- }
60727
- return null;
60728
- }
60729
- function findRetainedFrameForRegion(registry2, latest, region) {
60730
- return findFallbackFrame(registry2, latest, { region, requireRetainedData: true });
60693
+ if (bindingKind === "implicit") implicitFrameBindings.add(bound);
60694
+ return bound;
60731
60695
  }
60732
60696
  function resolveFramePixelTarget(target, context) {
60733
60697
  const bound = bindFramePixelTarget(target, context);
60734
- const latest = context.frame_registry.resolveForAction(bound.frame_id);
60735
- if (!pixelInsideFrame(latest, bound.x, bound.y)) {
60736
- const fallback = findFallbackFrame(context.frame_registry, latest, {
60737
- pixel: { x: bound.x, y: bound.y }
60738
- });
60739
- if (fallback) {
60740
- return {
60741
- frame_id: fallback.frame_id,
60742
- point: projectFramePixelToPointer(fallback, { x: bound.x, y: bound.y }),
60743
- pixel_space_fallback: {
60744
- latest_delivered: {
60745
- width: latest.delivered.width,
60746
- height: latest.delivered.height
60747
- },
60748
- fallback_frame_delivered: {
60749
- width: fallback.delivered.width,
60750
- height: fallback.delivered.height
60751
- }
60752
- }
60753
- };
60754
- }
60755
- const retainedSizes = context.frame_registry.retainedActionableFramesNewestFirst().map(
60756
- (frame) => `${frame.delivered.width}x${frame.delivered.height}`
60757
- ).join(", ");
60758
- throw new RangeError(
60759
- `frame pixel coordinate (${String(bound.x)}, ${String(bound.y)}) is outside ${latest.delivered.width}x${latest.delivered.height}` + (retainedSizes.length > 0 ? ` (no retained raster contains this pixel; retained: ${retainedSizes})` : "")
60760
- );
60761
- }
60698
+ const frame = context.frame_registry.resolveForAction(bound.frame_id);
60762
60699
  return {
60763
60700
  frame_id: bound.frame_id,
60764
- point: projectFramePixelToPointer(latest, {
60701
+ point: projectFramePixelToPointer(frame, {
60765
60702
  x: bound.x,
60766
60703
  y: bound.y
60767
60704
  })
@@ -60904,7 +60841,10 @@ var targetArgJSONSchema = {
60904
60841
  };
60905
60842
  var OPEN_APPLICATION_APP_PROPERTIES = {
60906
60843
  bundle_id: { type: "string", description: "macOS bundle id, e.g. com.google.Chrome" },
60907
- name: { type: "string", description: "application name, e.g. Google Chrome" },
60844
+ name: {
60845
+ type: "string",
60846
+ description: 'Copy the user-provided application name character-for-character. For example, use {"name":"\u7F51\u6613\u4E91\u97F3\u4E50app"}, not {"name":"\u7F51\u6613\u4E91\u97F3\u4E50"}; use {"name":"\u65E5\u5386"}, not {"name":"Calendar"}.'
60847
+ },
60908
60848
  pid: { type: "integer", description: "running process id from list_apps/get_app_state" },
60909
60849
  url: { type: "string", description: "single URL to hand to the app" },
60910
60850
  urls: {
@@ -61058,39 +60998,18 @@ function boundsNear(a, b, maxPx = HEAL_MAX_DISPLACEMENT_PX) {
61058
60998
  const dy = ca.y - cb.y;
61059
60999
  return Math.sqrt(dx * dx + dy * dy) <= maxPx;
61060
61000
  }
61061
- function captureFingerprint(element, bundleId) {
61001
+ function captureFingerprint(element, bundleId, surface) {
61062
61002
  return {
61063
61003
  role: element.role,
61064
61004
  title: normalizeTitle(element.title),
61065
61005
  value: normalizeValue(element.value),
61066
61006
  bounds: element.bounds,
61067
61007
  editable: element.editable,
61068
- bundle_id: typeof bundleId === "string" ? bundleId : ""
61008
+ bundle_id: typeof bundleId === "string" ? bundleId : "",
61009
+ actual_window_id: surface?.actual_window_id ?? null,
61010
+ presentation_window_id: surface?.presentation_window_id ?? null
61069
61011
  };
61070
61012
  }
61071
- var HEAL_AX_ERRORS = /* @__PURE__ */ new Set([
61072
- "invalid_element",
61073
- "cannot_complete"
61074
- ]);
61075
- function extractAxError(message) {
61076
- const m = /axError=([a-zA-Z_][a-zA-Z0-9_]*)/.exec(message);
61077
- return m ? m[1] : null;
61078
- }
61079
- function extractStructuredAxError(err) {
61080
- const detail = err.details.ax_error ?? err.details.axError;
61081
- return typeof detail === "string" && detail.length > 0 ? detail : null;
61082
- }
61083
- function isStructuredLookupStale(err) {
61084
- return err.details.action_sent === false && err.details.element_lookup === "not_found" && err.details.recovery === "reresolve_element" && err.details.auto_reresolve === true;
61085
- }
61086
- function isReresolvableBrokerError(err) {
61087
- if (!(err instanceof PermissionBrokerError)) return false;
61088
- if (err.code !== "element_unavailable") return false;
61089
- if (isStructuredLookupStale(err)) return true;
61090
- if (err.details.action_sent !== false) return false;
61091
- const axError = extractStructuredAxError(err) ?? extractAxError(err.message);
61092
- return axError !== null && HEAL_AX_ERRORS.has(axError);
61093
- }
61094
61013
  function findFingerprintMatch(stored, candidates, options = {}) {
61095
61014
  if (!stored.title) {
61096
61015
  return null;
@@ -61177,12 +61096,25 @@ async function captureFreshElements(deps, appRef2) {
61177
61096
  if (!raw || typeof raw !== "object") return null;
61178
61097
  const elements = raw.elements;
61179
61098
  if (!Array.isArray(elements)) return null;
61180
- return elements.map((entry) => normalizeCandidate(entry));
61099
+ const window2 = raw.window;
61100
+ const windowRecord = window2 && typeof window2 === "object" && !Array.isArray(window2) ? window2 : {};
61101
+ return {
61102
+ elements: elements.map((entry) => normalizeCandidate(entry)),
61103
+ actual_window_id: typeof windowRecord.actual_window_id === "number" ? windowRecord.actual_window_id : typeof windowRecord.window_id === "number" ? windowRecord.window_id : null,
61104
+ presentation_window_id: typeof windowRecord.presentation_window_id === "number" ? windowRecord.presentation_window_id : typeof windowRecord.window_id === "number" ? windowRecord.window_id : null
61105
+ };
61106
+ }
61107
+ function freshSurfaceMatches(stored, fresh) {
61108
+ const storedIsAttachedSurface = stored.actual_window_id !== null && stored.actual_window_id !== void 0 && stored.presentation_window_id !== null && stored.presentation_window_id !== void 0 && stored.actual_window_id !== stored.presentation_window_id;
61109
+ if (!storedIsAttachedSurface && fresh.actual_window_id === null && fresh.presentation_window_id === null) {
61110
+ return true;
61111
+ }
61112
+ return (stored.actual_window_id === null || stored.actual_window_id === void 0 || stored.actual_window_id === fresh.actual_window_id) && (stored.presentation_window_id === null || stored.presentation_window_id === void 0 || stored.presentation_window_id === fresh.presentation_window_id);
61181
61113
  }
61182
61114
  async function captureFreshFingerprintMatch(deps, ctx) {
61183
61115
  const fresh = await captureFreshElements(deps, ctx.appRef);
61184
- if (!fresh) return null;
61185
- return findFingerprintMatch(ctx.fingerprint, fresh);
61116
+ if (!fresh || !freshSurfaceMatches(ctx.fingerprint, fresh)) return null;
61117
+ return findFingerprintMatch(ctx.fingerprint, fresh.elements);
61186
61118
  }
61187
61119
  function normalizeCandidate(entry) {
61188
61120
  if (!entry || typeof entry !== "object") {
@@ -61228,26 +61160,6 @@ function asBounds2(value) {
61228
61160
  if (!nums.every((n) => Number.isFinite(n))) return [0, 0, 0, 0];
61229
61161
  return nums;
61230
61162
  }
61231
- async function callWithElementReresolution(deps, ctx, initialHandle, op, options = {}) {
61232
- try {
61233
- const result = await op(initialHandle);
61234
- return { result, info: null };
61235
- } catch (err) {
61236
- if (!isReresolvableBrokerError(err)) throw err;
61237
- const fresh = await captureFreshElements(deps, ctx.appRef);
61238
- if (!fresh) throw err;
61239
- const info = findFingerprintMatch(ctx.fingerprint, fresh, {
61240
- singleWindowApp: options.singleWindowApp
61241
- });
61242
- if (!info) throw err;
61243
- const result = await op({ native: info.native, bounds: info.bounds });
61244
- return { result, info };
61245
- }
61246
- }
61247
- function formatReresolvedNote(info) {
61248
- if (!info) return "";
61249
- return ` (auto_reresolved: ${info.match_criteria}, ${info.confidence} confidence)`;
61250
- }
61251
61163
  var TargetResolveError = class extends Error {
61252
61164
  reason;
61253
61165
  stateId;
@@ -61334,13 +61246,17 @@ function buildFromElement(element, state) {
61334
61246
  state.state_id
61335
61247
  );
61336
61248
  }
61337
- resolution.fingerprint = captureFingerprint(element, state.app.bundle_id);
61249
+ resolution.fingerprint = captureFingerprint(element, state.app.bundle_id, {
61250
+ actual_window_id: state.window.actual_window_id ?? state.window.window_id,
61251
+ presentation_window_id: state.window.presentation_window_id ?? state.window.window_id
61252
+ });
61338
61253
  return resolution;
61339
61254
  }
61340
- function resolveCoordinate(target, ctx) {
61255
+ function resolveCoordinate(target, ctx, bindingKind) {
61341
61256
  try {
61342
- const { frame_id, point, pixel_space_fallback } = resolveFramePixelTarget(target, {
61343
- frame_registry: ctx.session.frameRegistry
61257
+ const { frame_id, point } = resolveFramePixelTarget(target, {
61258
+ frame_registry: ctx.session.frameRegistry,
61259
+ binding_kind: bindingKind
61344
61260
  });
61345
61261
  const frame = ctx.session.frameRegistry.get(frame_id);
61346
61262
  if (frame) recordTargetAppDisplayEvidence(frame.app);
@@ -61350,12 +61266,7 @@ function resolveCoordinate(target, ctx) {
61350
61266
  ...frame.window.window_id !== null ? { window_id: frame.window.window_id } : {}
61351
61267
  } : {};
61352
61268
  const app_ref = Object.keys(appRef2).length > 0 ? appRef2 : null;
61353
- const resolution = { point, app_ref, isElement: false, kind: "coordinate" };
61354
- if (pixel_space_fallback) {
61355
- const { latest_delivered, fallback_frame_delivered } = pixel_space_fallback;
61356
- resolution.coordinate_frame_note = `Coordinate (${target.x}, ${target.y}) was outside the latest delivered raster ${latest_delivered.width}x${latest_delivered.height} (e.g. a zoom crop); it was projected through the retained ${fallback_frame_delivered.width}x${fallback_frame_delivered.height} raster instead.`;
61357
- }
61358
- return resolution;
61269
+ return { point, app_ref, isElement: false, kind: "coordinate" };
61359
61270
  } catch (error51) {
61360
61271
  throw new TargetResolveError(
61361
61272
  "frame_reference_invalid",
@@ -61364,11 +61275,13 @@ function resolveCoordinate(target, ctx) {
61364
61275
  }
61365
61276
  }
61366
61277
  function resolveTarget(target, ctx) {
61278
+ const originalBindingKind = frameBindingKind(target);
61367
61279
  const parsed = parseTarget(target);
61368
61280
  if (parsed.type === "element") {
61369
61281
  return resolveElement(parsed, ctx);
61370
61282
  }
61371
- return resolveCoordinate(parsed, ctx);
61283
+ const bindingKind = target && typeof target === "object" && originalBindingKind === "implicit" && typeof target.frame_id === "string" ? originalBindingKind : frameBindingKind(parsed);
61284
+ return resolveCoordinate(parsed, ctx, bindingKind);
61372
61285
  }
61373
61286
  function displayTopologyFingerprint(displays) {
61374
61287
  return [...displays].sort((left, right) => left.id - right.id).map(
@@ -61655,10 +61568,16 @@ function stringifiedJsonArray(schema) {
61655
61568
  }
61656
61569
  }, schema);
61657
61570
  }
61571
+ var applicationName = external_exports.string().describe(
61572
+ 'For an app that is not running, copy the user-provided name character-for-character, including script, case, spaces, punctuation, and suffixes such as app. For example, use {"name":"\u7F51\u6613\u4E91\u97F3\u4E50app"}, not {"name":"\u7F51\u6613\u4E91\u97F3\u4E50"}; use {"name":"\u65E5\u5386"}, not {"name":"Calendar"}. Do not translate, localize, normalize, shorten, or remove a suffix.'
61573
+ );
61658
61574
  var sharedAppProperties = {
61659
61575
  bundle_id: external_exports.string().optional(),
61660
- name: external_exports.string().optional(),
61576
+ name: applicationName.optional(),
61661
61577
  pid: external_exports.number().int().optional(),
61578
+ window_id: external_exports.number().int().positive().optional().describe(
61579
+ "Only copy a fresh actual_window_id from an observed macOS open/save panel. Omit for ordinary launch or activation; never guess a placeholder such as 1."
61580
+ ),
61662
61581
  url: external_exports.string().optional(),
61663
61582
  urls: stringifiedJsonArray(external_exports.array(external_exports.string())).optional()
61664
61583
  };
@@ -61668,7 +61587,7 @@ var bundleBranch = external_exports.object({
61668
61587
  }).strict();
61669
61588
  var nameBranch = external_exports.object({
61670
61589
  ...sharedAppProperties,
61671
- name: external_exports.string()
61590
+ name: applicationName
61672
61591
  }).strict();
61673
61592
  var pidBranch = external_exports.object({
61674
61593
  ...sharedAppProperties,
@@ -61682,7 +61601,6 @@ var listAppsSchema = external_exports.object({}).strict();
61682
61601
  var openApplicationSchema = external_exports.object({
61683
61602
  app: openApplicationAppArg,
61684
61603
  activate: external_exports.boolean().default(false),
61685
- confirm_focus_steal: external_exports.boolean().default(false),
61686
61604
  new_instance: external_exports.boolean().default(false).describe(
61687
61605
  "macOS only: launch a separate process and verify its fresh pid. Use for an isolated scratch app when an existing instance is blocked; do not combine with app.pid."
61688
61606
  )
@@ -61720,7 +61638,7 @@ var clickShape = {
61720
61638
  target: targetArg,
61721
61639
  modifiers: external_exports.string().trim().default(""),
61722
61640
  strategy: strategyEnum.default("auto"),
61723
- return_state: returnStateEnum.default("compact"),
61641
+ return_state: returnStateEnum.default("none"),
61724
61642
  app_ref: appRefNullable
61725
61643
  };
61726
61644
  var leftClickSchema = external_exports.object(clickShape).strict();
@@ -61733,14 +61651,14 @@ var scrollSchema = external_exports.object({
61733
61651
  scroll_direction: scrollDirectionEnum,
61734
61652
  scroll_amount: numInt,
61735
61653
  strategy: strategyEnum.default("auto"),
61736
- return_state: returnStateEnum.default("compact"),
61654
+ return_state: returnStateEnum.default("none"),
61737
61655
  app_ref: appRefNullable
61738
61656
  }).strict();
61739
61657
  var leftClickDragSchema = external_exports.object({
61740
61658
  from_target: targetArg,
61741
61659
  to: targetArg,
61742
61660
  modifiers: external_exports.string().trim().default(""),
61743
- return_state: returnStateEnum.default("compact"),
61661
+ return_state: returnStateEnum.default("none"),
61744
61662
  app_ref: appRefNullable
61745
61663
  }).strict();
61746
61664
  var mouseMoveSchema = external_exports.object({
@@ -61751,10 +61669,10 @@ var mouseMoveSchema = external_exports.object({
61751
61669
  var leftMouseDownSchema = external_exports.object({
61752
61670
  target: targetArg,
61753
61671
  app_ref: appRefNullable,
61754
- return_state: returnStateEnum.default("compact")
61672
+ return_state: returnStateEnum.default("none")
61755
61673
  }).strict();
61756
61674
  var leftMouseUpSchema = external_exports.object({
61757
- return_state: returnStateEnum.default("compact")
61675
+ return_state: returnStateEnum.default("none")
61758
61676
  }).strict();
61759
61677
  var PUBLIC_KEY_TOKENS = /* @__PURE__ */ new Set([
61760
61678
  ..."abcdefghijklmnopqrstuvwxyz0123456789".split(""),
@@ -61813,34 +61731,34 @@ var typeSchema = external_exports.object({
61813
61731
  target: targetArgNullable,
61814
61732
  app_ref: appRefNullable,
61815
61733
  strategy: strategyEnum.default("auto"),
61816
- return_state: returnStateEnum.default("compact")
61734
+ return_state: returnStateEnum.default("none")
61817
61735
  }).strict();
61818
61736
  var setValueSchema = external_exports.object({
61819
61737
  // Coordinate targets are hit-tested to their owning element first.
61820
61738
  target: targetArg,
61821
61739
  value: external_exports.string(),
61822
61740
  strategy: strategyEnum.default("auto"),
61823
- return_state: returnStateEnum.default("compact")
61741
+ return_state: returnStateEnum.default("none")
61824
61742
  }).strict();
61825
61743
  var selectTextSchema = external_exports.object({
61826
61744
  // Coordinate targets are hit-tested to their owning element first.
61827
61745
  target: targetArg,
61828
61746
  text_range: stringifiedJsonArray(external_exports.array(numInt).length(2)).nullish(),
61829
- return_state: returnStateEnum.default("compact")
61747
+ return_state: returnStateEnum.default("none")
61830
61748
  }).strict();
61831
61749
  var keySchema = external_exports.object({
61832
61750
  text: external_exports.string(),
61833
61751
  repeat: numInt.nullish(),
61834
61752
  app_ref: appRefNullable,
61835
61753
  strategy: strategyEnum.default("auto"),
61836
- return_state: returnStateEnum.default("compact")
61754
+ return_state: returnStateEnum.default("none")
61837
61755
  }).strict();
61838
61756
  var holdKeySchema = external_exports.object({
61839
61757
  text: external_exports.string(),
61840
61758
  duration: finiteFloat,
61841
61759
  app_ref: appRefNullable,
61842
61760
  strategy: strategyEnum.default("auto"),
61843
- return_state: returnStateEnum.default("compact")
61761
+ return_state: returnStateEnum.default("none")
61844
61762
  }).strict();
61845
61763
  var performActionSchema = external_exports.object({
61846
61764
  // Coordinate targets are accepted and routed through the a11y hit-test
@@ -61848,7 +61766,7 @@ var performActionSchema = external_exports.object({
61848
61766
  // refused at runtime with a soft error.
61849
61767
  target: targetArg,
61850
61768
  action: external_exports.string(),
61851
- return_state: returnStateEnum.default("compact")
61769
+ return_state: returnStateEnum.default("none")
61852
61770
  }).strict();
61853
61771
  var requestAccessSchema = external_exports.object({
61854
61772
  capabilities: stringifiedJsonArray(external_exports.array(external_exports.string())).nullish()
@@ -61884,7 +61802,6 @@ async function composeZoom(deps, args, options) {
61884
61802
  let cropScreenBounds = null;
61885
61803
  let targetFingerprint = null;
61886
61804
  let targetNative = null;
61887
- let sourceFrameFallbackNote = null;
61888
61805
  if (args.target) {
61889
61806
  if (args.region) throw new Error(ZOOM_ERR_BOTH);
61890
61807
  const resolved = resolveTarget(args.target, { session });
@@ -61911,17 +61828,10 @@ async function composeZoom(deps, args, options) {
61911
61828
  }
61912
61829
  cropScreenBounds = [x0, y0, x1, y1];
61913
61830
  sourceFrame = args.frame_id ? session.frameRegistry.resolveForAction(args.frame_id) : session.frameRegistry.resolveLatestForAction();
61914
- if (!args.frame_id && (x0 < 0 || y0 < 0 || x1 > sourceFrame.delivered.width || y1 > sourceFrame.delivered.height)) {
61915
- const fallback = findRetainedFrameForRegion(session.frameRegistry, sourceFrame, [
61916
- x0,
61917
- y0,
61918
- x1,
61919
- y1
61920
- ]);
61921
- if (fallback) {
61922
- sourceFrameFallbackNote = `The requested region ${JSON.stringify(cropScreenBounds)} was not fully inside the latest delivered raster ${sourceFrame.delivered.width}x${sourceFrame.delivered.height} (e.g. a zoom crop); it was cropped from the retained ${fallback.delivered.width}x${fallback.delivered.height} raster instead.`;
61923
- sourceFrame = fallback;
61924
- }
61831
+ if (x0 < 0 || y0 < 0 || x1 > sourceFrame.delivered.width || y1 > sourceFrame.delivered.height) {
61832
+ throw new RangeError(
61833
+ `zoom: region ${JSON.stringify(args.region)} is outside latest delivered raster ${sourceFrame.delivered.width}x${sourceFrame.delivered.height}`
61834
+ );
61925
61835
  }
61926
61836
  recordTargetAppDisplayEvidence(sourceFrame.app);
61927
61837
  if (!sourceFrame.delivered.data) {
@@ -62130,17 +62040,12 @@ async function composeZoom(deps, args, options) {
62130
62040
  actionable: windowGeometryVerified,
62131
62041
  non_actionable_reason: windowGeometryVerified ? null : captureAppRaw?.screenshot_blank === true ? "screenshot_blank" : "capture_geometry_unverified"
62132
62042
  });
62133
- const hint = `Zoom image ${encoded.finalWidth}x${encoded.finalHeight}px. For a pixel coordinate chosen from THIS returned zoom image, call tools with {"type":"coordinate","x":...,"y":...}. Choose x/y only by looking at this returned Zoom raster and submit them unchanged; frame binding is internal. CUA owns every crop, scale, and native projection.`;
62134
62043
  const textBlocks = [];
62135
- if (sourceFrameFallbackNote) {
62136
- textBlocks.push(sourceFrameFallbackNote);
62137
- }
62138
62044
  if (clamped) {
62139
62045
  textBlocks.push(
62140
62046
  "The crop was clipped to the captured window; part of the requested region or element was outside the window."
62141
62047
  );
62142
62048
  }
62143
- textBlocks.push(hint);
62144
62049
  return {
62145
62050
  image,
62146
62051
  image_ref: frameDescriptor.image_ref,
@@ -62510,11 +62415,6 @@ function imageBlock(data, format) {
62510
62415
  function imageRefBlock(imageRef) {
62511
62416
  return textBlock(JSON.stringify({ image_ref: imageRef }));
62512
62417
  }
62513
- function frameActionHint() {
62514
- return textBlock(
62515
- "For pixel action, act before another visual observation. Choose x/y only by looking at THIS returned raster. Submit them unchanged; frame binding is internal. Do not invent or transform coordinates."
62516
- );
62517
- }
62518
62418
  function imageWithRef(imageRef, data, format) {
62519
62419
  if (imageRef.actionable !== true) {
62520
62420
  return [
@@ -62523,7 +62423,7 @@ function imageWithRef(imageRef, data, format) {
62523
62423
  )
62524
62424
  ];
62525
62425
  }
62526
- return [imageBlock(data, format), imageRefBlock(imageRef), frameActionHint()];
62426
+ return [imageBlock(data, format), imageRefBlock(imageRef)];
62527
62427
  }
62528
62428
  function withOfficialFrameIntegrity(result, imageRef, data, format, session) {
62529
62429
  const frame = session.frameRegistry.get(imageRef.frame_id);
@@ -62537,7 +62437,7 @@ function withOfficialFrameIntegrity(result, imageRef, data, format, session) {
62537
62437
  return {
62538
62438
  ...result,
62539
62439
  _meta: {
62540
- ...result._meta ?? {},
62440
+ ...result._meta,
62541
62441
  [OFFICIAL_CUA_FRAME_INTEGRITY_META_KEY]: {
62542
62442
  version: 1,
62543
62443
  frame_id: imageRef.frame_id,
@@ -62566,30 +62466,6 @@ function toText(value) {
62566
62466
  if (typeof value === "string") return value;
62567
62467
  return JSON.stringify(value);
62568
62468
  }
62569
- var screenshotArtifactCounter = 0;
62570
- var screenshotArtifactDir = null;
62571
- function ensureScreenshotArtifactDir() {
62572
- if (screenshotArtifactDir) return screenshotArtifactDir;
62573
- const dir = mkdtempSync(join3(tmpdir2(), "zcode-cua-shot-"));
62574
- chmodSync2(dir, 448);
62575
- screenshotArtifactDir = dir;
62576
- process.once("exit", () => {
62577
- rmSync2(dir, { recursive: true, force: true });
62578
- });
62579
- return dir;
62580
- }
62581
- function writeScreenshotArtifact(bytes) {
62582
- try {
62583
- const path = join3(ensureScreenshotArtifactDir(), `shot-${screenshotArtifactCounter++}.jpg`);
62584
- writeFileSync2(path, bytes, { flag: "wx", mode: 384 });
62585
- return path;
62586
- } catch {
62587
- return "";
62588
- }
62589
- }
62590
- function screenshotCoordinateHint(width, height) {
62591
- return `Full-screen screenshot ${width}x${height}px. Prefer get_app_state and act via an element target {"type":"element","state_id":...,"index":N} from that state. For a pixel coordinate read off THIS exact screenshot, pass {"type":"coordinate","x":...,"y":...}. Choose x/y only by looking at THIS returned raster. Submit them unchanged; frame binding is internal and CUA owns the native projection.`;
62592
- }
62593
62469
  function mapAppStateResult(result) {
62594
62470
  if (typeof result === "string") return textResult(result);
62595
62471
  if (result === null || typeof result !== "object") return textResult(toText(result));
@@ -62623,96 +62499,14 @@ async function mapRawCaptureAppResult(result, detail, includeTree, options) {
62623
62499
  }
62624
62500
  }
62625
62501
  const session = options?.session ?? getDefaultSession();
62626
- const reusableStateId = session.lastStateIdFor(
62627
- raw.app && typeof raw.app === "object" ? raw.app : {},
62628
- raw.window && typeof raw.window === "object" ? raw.window : {}
62629
- );
62630
- if (raw.snapshot_mode === "delta" && raw.changes) {
62631
- noteObservation(raw, session);
62632
- const reuseId = reusableStateId;
62633
- const lines = [];
62634
- lines.push(
62635
- `state_id=${reuseId ?? "?"} mode=delta` + (reuseId ? ` (reuse state_id ${reuseId} for element targets; changed elements may be stale \u2014 re-observe full if unsure)` : "")
62636
- );
62637
- if (raw.changes.updated && raw.changes.updated.length > 0) {
62638
- lines.push(`Updated (${raw.changes.updated_count}):`);
62639
- for (const u of raw.changes.updated) {
62640
- const fields = Object.entries(u.changes).map(([k, v]) => `${k}=${JSON.stringify(v)}`);
62641
- lines.push(` ~ [${u.index}] ${u.role} "${u.title ?? ""}" ${fields.join(" ")}`);
62642
- }
62643
- }
62644
- if (raw.changes.added && raw.changes.added.length > 0) {
62645
- lines.push(`Added (${raw.changes.added_count}):`);
62646
- for (const a of raw.changes.added) {
62647
- lines.push(` + [${a.index}] ${a.role} "${a.title ?? ""}"`);
62648
- }
62649
- }
62650
- if (raw.changes.removed && raw.changes.removed.length > 0) {
62651
- lines.push(`Removed (${raw.changes.removed_count}):`);
62652
- for (const r of raw.changes.removed) {
62653
- lines.push(` - ${r.role} "${r.title ?? ""}"`);
62654
- }
62655
- }
62656
- if (raw.changes.focus_changed) {
62657
- lines.push(`@focus ${raw.changes.focused_title ?? "(unknown)"}`);
62658
- }
62659
- return { content: [textBlock(lines.join("\n"))] };
62660
- }
62661
- if (raw.snapshot_mode === "no_change") {
62662
- noteObservation(raw, session);
62663
- const reuseId = reusableStateId;
62664
- const content2 = [];
62665
- let emittedFrame2;
62666
- const screenshot2 = raw.screenshot;
62667
- if (raw.screenshot_blank !== true && typeof screenshot2?.data === "string" && screenshot2.data) {
62668
- const cached2 = reuseId ? session.get(reuseId) : null;
62669
- if (cached2) {
62670
- const imageRef = await issueCaptureFrame(
62671
- raw,
62672
- cached2.app,
62673
- cached2.window,
62674
- session
62675
- );
62676
- if (imageRef) {
62677
- const format = screenshot2.format ?? "jpeg";
62678
- content2.push(...imageWithRef(imageRef, screenshot2.data, format));
62679
- if (imageRef.actionable) {
62680
- emittedFrame2 = { imageRef, data: screenshot2.data, format };
62681
- }
62682
- }
62683
- }
62684
- }
62685
- if (raw.screenshot_blank === true) {
62686
- content2.push(
62687
- textBlock(
62688
- "[screenshot_blank] The requested screenshot is BLANK/unusable. Do NOT read coordinates or visual content from it; use the existing accessibility state or bring the app to the foreground and observe again."
62689
- )
62690
- );
62691
- }
62692
- content2.push(
62693
- textBlock(
62694
- `state_id=${reuseId ?? "?"} mode=no_change
62695
- No accessibility tree changes since last observation. Act now` + (reuseId ? ` (reuse element targets from state_id ${reuseId}).` : ".")
62696
- )
62697
- );
62698
- const result2 = { content: content2 };
62699
- return emittedFrame2 ? withOfficialFrameIntegrity(
62700
- result2,
62701
- emittedFrame2.imageRef,
62702
- emittedFrame2.data,
62703
- emittedFrame2.format,
62704
- session
62705
- ) : result2;
62706
- }
62502
+ if (raw.snapshot_mode === "delta" || raw.snapshot_mode === "no_change") return null;
62707
62503
  if (!Array.isArray(raw.elements)) return null;
62708
62504
  if (typeof raw.app !== "object" || typeof raw.window !== "object") return null;
62709
62505
  const state = await ingestCaptureAppResult(
62710
62506
  raw,
62711
62507
  { session }
62712
62508
  );
62713
- const repeatCount = noteObservation(raw, session);
62714
- const isRepeat = repeatCount >= 2;
62715
- const suppressRepeatSignal = options?.settle === true;
62509
+ noteObservation(raw, session);
62716
62510
  const content = [];
62717
62511
  let emittedFrame;
62718
62512
  const screenshot = raw.screenshot;
@@ -62729,7 +62523,7 @@ No accessibility tree changes since last observation. Act now` + (reuseId ? ` (r
62729
62523
  if (screenshotBlank) {
62730
62524
  content.push(
62731
62525
  textBlock(
62732
- "[screenshot_blank] The get_app_state screenshot is BLANK (transparent or near-black placeholder). The target window was most likely occluded, minimized, off-screen, or mid-render at capture time, so these pixels are unusable \u2014 do NOT read coordinates or content from this image. Re-foreground the app (open_application with activate, or click its Dock icon/window) and call get_app_state again, or use the accessibility tree returned with this observation, which is independent of the pixels. The attached image is only evidence that the pixel capture was blank."
62526
+ "[screenshot_blank] The get_app_state screenshot is BLANK (transparent or near-black placeholder). The target window was most likely occluded, minimized, off-screen, or mid-render at capture time, so these pixels are unusable \u2014 do NOT read coordinates or content from this image. The blank raster and image_ref were withheld. Use the accessibility tree returned with this observation, or call open_application(activate=true) when foreground recovery is required, then call get_app_state again."
62733
62527
  )
62734
62528
  );
62735
62529
  }
@@ -62751,16 +62545,6 @@ No accessibility tree changes since last observation. Act now` + (reuseId ? ` (r
62751
62545
  }
62752
62546
  }
62753
62547
  }
62754
- if (isRepeat && !suppressRepeatSignal) {
62755
- content.push(
62756
- textBlock(
62757
- JSON.stringify({
62758
- repeat_observation: true,
62759
- repeated_observations: repeatCount
62760
- })
62761
- )
62762
- );
62763
- }
62764
62548
  const mappedResult = { content };
62765
62549
  return emittedFrame ? withOfficialFrameIntegrity(
62766
62550
  mappedResult,
@@ -62770,142 +62554,33 @@ No accessibility tree changes since last observation. Act now` + (reuseId ? ` (r
62770
62554
  session
62771
62555
  ) : mappedResult;
62772
62556
  }
62773
- var POST_ACTION_SETTLE_ATTEMPTS = 2;
62774
- var POST_ACTION_SETTLE_INTERVAL_MS = 120;
62775
- function rawDigest(raw) {
62776
- if (!raw || typeof raw !== "object") return "empty";
62777
- const elements = raw.elements;
62778
- if (!Array.isArray(elements)) return "no-elements";
62779
- let acc = `n=${elements.length}`;
62780
- for (const el of elements) {
62781
- if (!el || typeof el !== "object") {
62782
- acc += "|?";
62783
- continue;
62784
- }
62785
- const e = el;
62786
- const b = Array.isArray(e.bounds) ? e.bounds.join(",") : "?";
62787
- acc += `|${e.role ?? ""}:${e.title ?? ""}:${e.value ?? ""}:${b}:${e.native ?? ""}`;
62557
+ function actionReceiptBlock(receipt) {
62558
+ const action_receipt = {
62559
+ schema_version: "zcode-cua-action-receipt-v1",
62560
+ action_sent: receipt.action_sent,
62561
+ dispatch_status: receipt.dispatch_status,
62562
+ retry_action: false
62563
+ };
62564
+ if (receipt.ax_error) action_receipt.ax_error = receipt.ax_error;
62565
+ if (receipt.target_verification_status) {
62566
+ action_receipt.target_verification_status = receipt.target_verification_status;
62788
62567
  }
62789
- return acc;
62568
+ return textBlock(JSON.stringify({ action_receipt }));
62790
62569
  }
62791
- function defaultSleepMs(ms) {
62792
- return new Promise((resolve22) => setTimeout(resolve22, ms));
62793
- }
62794
- async function captureSettledRaw(deps, app_ref, sleep = defaultSleepMs) {
62795
- const first = await callBroker(
62796
- deps,
62797
- "capture_app",
62798
- { app_ref, include_screenshot: false },
62799
- { kind: "read", timeoutMs: CAPTURE_APP_TIMEOUT_MS }
62570
+ function stateUnavailableBlock(error51) {
62571
+ const errorType = error51 instanceof Error ? error51.constructor.name : typeof error51;
62572
+ const message = error51 instanceof Error ? error51.message : String(error51);
62573
+ return textBlock(
62574
+ JSON.stringify({
62575
+ state_observation: {
62576
+ schema_version: "zcode-cua-state-observation-v1",
62577
+ status: "unavailable",
62578
+ retry_action: false,
62579
+ error_type: errorType,
62580
+ message
62581
+ }
62582
+ })
62800
62583
  );
62801
- if (POST_ACTION_SETTLE_ATTEMPTS <= 1) return first;
62802
- const baseline = rawDigest(first);
62803
- let previous = baseline;
62804
- let changed = false;
62805
- let raw = first;
62806
- let latestEvidence = isNoChangeSnapshot(first) ? null : first;
62807
- for (let i = 0; i < POST_ACTION_SETTLE_ATTEMPTS - 1; i++) {
62808
- await sleep(POST_ACTION_SETTLE_INTERVAL_MS);
62809
- const nextRaw = await callBroker(
62810
- deps,
62811
- "capture_app",
62812
- { app_ref, include_screenshot: false },
62813
- { kind: "read", timeoutMs: CAPTURE_APP_TIMEOUT_MS }
62814
- );
62815
- const nextDigest = rawDigest(nextRaw);
62816
- if (!isNoChangeSnapshot(nextRaw)) latestEvidence = nextRaw;
62817
- if (nextDigest !== baseline) changed = true;
62818
- if (changed && nextDigest === previous) return latestEvidence ?? nextRaw;
62819
- previous = nextDigest;
62820
- raw = nextRaw;
62821
- }
62822
- return latestEvidence ?? raw;
62823
- }
62824
- async function ensureActionableFullSnapshot(deps, app_ref, raw) {
62825
- const snapshotMode = raw !== null && typeof raw === "object" ? raw.snapshot_mode : void 0;
62826
- if (snapshotMode !== "delta" && snapshotMode !== "no_change") return raw;
62827
- try {
62828
- const refreshed = await callBroker(
62829
- deps,
62830
- "capture_app",
62831
- { app_ref, include_screenshot: false, force_full: true },
62832
- { kind: "read", timeoutMs: CAPTURE_APP_TIMEOUT_MS }
62833
- );
62834
- if (!isFullCaptureSnapshot(refreshed)) return raw;
62835
- return refreshed;
62836
- } catch {
62837
- return raw;
62838
- }
62839
- }
62840
- function isFullCaptureSnapshot(raw) {
62841
- if (raw === null || typeof raw !== "object") return false;
62842
- const candidate = raw;
62843
- return candidate.snapshot_mode !== "delta" && candidate.snapshot_mode !== "no_change" && candidate.app !== null && typeof candidate.app === "object" && candidate.window !== null && typeof candidate.window === "object" && Array.isArray(candidate.elements);
62844
- }
62845
- function isNoChangeSnapshot(raw) {
62846
- return raw !== null && typeof raw === "object" && raw.snapshot_mode === "no_change";
62847
- }
62848
- function classifyReobserveFailure(e) {
62849
- const msg = e instanceof Error ? e.message : String(e);
62850
- const errorType = e instanceof Error ? e.constructor.name : typeof e;
62851
- const lower = msg.toLowerCase();
62852
- if (/\bwindow\b/.test(lower) && /(clos|replac|exit|gone|missing)/.test(lower)) {
62853
- return {
62854
- reason: "window_targeting_error",
62855
- suggested_action: "The window may have closed, been replaced, or the app exited. Call list_windows (or get_app_state) to see the current windows before the next step.",
62856
- warning: "The action was sent but its result could not be verified against the requested window. Check list_windows before continuing; do not retry the action itself.",
62857
- errorType
62858
- };
62859
- }
62860
- if (/(state_id|state expired|stale|evicted)/.test(lower)) {
62861
- return {
62862
- reason: "state_expired",
62863
- suggested_action: "The observed state_id is stale or expired. Call get_app_state again to refresh; do not retry the action itself.",
62864
- warning: "The action was sent but its result could not be verified because the observation state expired. Re-observe with get_app_state.",
62865
- errorType
62866
- };
62867
- }
62868
- if (/(permission|not authorized|notattrusted|tcc|accessibility)/.test(lower)) {
62869
- return {
62870
- reason: "permission_regression",
62871
- suggested_action: "A permission blocked the post-action re-observe (Accessibility/Input may have been revoked or changed owner). Call request_access to inspect the permission status; do not retry the action itself.",
62872
- warning: "The action was sent but its result could not be verified because a permission blocked the re-observe. Check permissions via request_access.",
62873
- errorType
62874
- };
62875
- }
62876
- return {
62877
- reason: "transient_reobserve_failed",
62878
- suggested_action: "This looks like a transient backend/AX error, not a permanent failure: one re-observe with get_app_state is safe. Do not retry the action itself.",
62879
- warning: "The action was sent but its result could not be verified due to a transient error. A single get_app_state re-observe is safe; do not auto-retry the action.",
62880
- errorType
62881
- };
62882
- }
62883
- function actionOutcomeBlock(verification_status, state_available, extra) {
62884
- const outcome = {
62885
- schema_version: "zcode-cua-action-outcome-v1",
62886
- action_sent: true,
62887
- verification_status,
62888
- state_available,
62889
- retry_action: false
62890
- };
62891
- if (extra?.verification_reason) outcome.verification_reason = extra.verification_reason;
62892
- if (extra?.warning) outcome.warning = extra.warning;
62893
- if (extra?.suggested_action) outcome.suggested_action = extra.suggested_action;
62894
- if (extra?.error_type) outcome.error_type = extra.error_type;
62895
- if (extra?.value_check) outcome.value_check = extra.value_check;
62896
- if (extra?.expected_value !== void 0) outcome.expected_value = extra.expected_value;
62897
- if (extra?.actual_value !== void 0) outcome.actual_value = extra.actual_value;
62898
- if (extra?.effect_status) outcome.effect_status = extra.effect_status;
62899
- if (extra?.dispatch_status) outcome.dispatch_status = extra.dispatch_status;
62900
- if (extra?.state_sync_status) outcome.state_sync_status = extra.state_sync_status;
62901
- if (extra?.pre_state_id) outcome.pre_state_id = extra.pre_state_id;
62902
- if (extra?.post_state_id) outcome.post_state_id = extra.post_state_id;
62903
- if (extra?.ax_error) outcome.ax_error = extra.ax_error;
62904
- if (extra?.effect_attribution) outcome.effect_attribution = extra.effect_attribution;
62905
- if (extra?.target_verification_status) {
62906
- outcome.target_verification_status = extra.target_verification_status;
62907
- }
62908
- return textBlock(JSON.stringify(outcome));
62909
62584
  }
62910
62585
  function normalizeActionDispatchReceipt(result) {
62911
62586
  if (result && typeof result === "object") {
@@ -62921,11 +62596,14 @@ function normalizeActionDispatchReceipt(result) {
62921
62596
  }
62922
62597
  return { action_sent: true, dispatch_status: "accepted" };
62923
62598
  }
62924
- function actionDispatchReceiptFromError(error51, context) {
62599
+ function actionDispatchReceiptFromError(error51) {
62925
62600
  const details = error51?.details;
62601
+ if (details?.action_sent === false && details.reason === "stale_element") {
62602
+ return { action_sent: false, dispatch_status: "not_sent" };
62603
+ }
62926
62604
  if (error51?.code === "broker_unavailable") {
62927
- if (details?.request_delivery_state === "possibly_sent" && context) {
62928
- toolSession(context.deps).markMutationDispatched(context.mutation);
62605
+ if (details?.request_delivery_state === "possibly_sent") {
62606
+ return { action_sent: true, dispatch_status: "possibly_sent" };
62929
62607
  }
62930
62608
  return null;
62931
62609
  }
@@ -62936,210 +62614,89 @@ function actionDispatchReceiptFromError(error51, context) {
62936
62614
  ...typeof details.ax_error === "string" ? { ax_error: details.ax_error } : {}
62937
62615
  };
62938
62616
  }
62939
- function unavailableEnvelope(note, reason, consistency) {
62940
- return textBlock(
62941
- JSON.stringify({
62942
- message: `${note} Call get_app_state to observe the result.`,
62943
- action_outcome: {
62944
- schema_version: "zcode-cua-action-outcome-v1",
62945
- action_sent: true,
62946
- verification_status: "unavailable",
62947
- state_available: false,
62948
- retry_action: false,
62949
- verification_reason: reason,
62950
- warning: "Call get_app_state only if a later step needs to observe the result.",
62951
- ...consistency ? {
62952
- dispatch_status: consistency.dispatch.dispatch_status,
62953
- state_sync_status: "refresh_required",
62954
- pre_state_id: consistency.mutation.preActionState?.state_id,
62955
- ...consistency.dispatch.ax_error ? { ax_error: consistency.dispatch.ax_error } : {},
62956
- effect_attribution: "not_proven"
62957
- } : {}
62958
- },
62959
- state: null
62960
- })
62961
- );
62962
- }
62963
- function failedEnvelope(note, failure, consistency) {
62964
- const lead = failure.reason === "window_targeting_error" ? `${note} The action was sent, but the post-action re-observe could not confirm the targeted window. ${failure.suggested_action}` : failure.reason === "state_expired" ? `${note} The action was sent, but the post-action re-observe found the referenced state stale. ${failure.suggested_action}` : failure.reason === "permission_regression" ? `${note} The action was sent, but the post-action re-observe was blocked by a permission error. ${failure.suggested_action}` : `${note} The action was sent, but post-action verification hit a transient error. ${failure.suggested_action}`;
62965
- return textBlock(
62966
- JSON.stringify({
62967
- message: lead,
62968
- action_outcome: {
62969
- schema_version: "zcode-cua-action-outcome-v1",
62970
- action_sent: true,
62971
- verification_status: "failed",
62972
- state_available: false,
62973
- retry_action: false,
62974
- verification_reason: failure.reason,
62975
- warning: failure.warning,
62976
- suggested_action: failure.suggested_action,
62977
- error_type: failure.errorType,
62978
- ...consistency ? {
62979
- dispatch_status: consistency.dispatch.dispatch_status,
62980
- state_sync_status: "refresh_required",
62981
- pre_state_id: consistency.mutation.preActionState?.state_id,
62982
- ...consistency.dispatch.ax_error ? { ax_error: consistency.dispatch.ax_error } : {},
62983
- effect_attribution: "not_proven"
62984
- } : {}
62985
- },
62986
- state: null
62987
- })
62988
- );
62989
- }
62990
- function checkSetValueResult(raw, verify) {
62991
- const rawObj = raw ?? {};
62992
- const fp = verify.fingerprint;
62993
- const expected = String(verify.expected);
62994
- const elements = Array.isArray(rawObj.elements) ? rawObj.elements : [];
62995
- if (elements.length) {
62996
- const fpBounds = Array.isArray(fp.bounds) ? fp.bounds.map(Number) : null;
62997
- const match = elements.find((el) => {
62998
- if (!el || typeof el !== "object") return false;
62999
- if (fp.role && el.role !== fp.role) return false;
63000
- if (!fpBounds) return false;
63001
- const b = Array.isArray(el.bounds) ? el.bounds.map(Number) : null;
63002
- if (!b || b.length !== fpBounds.length) return false;
63003
- return b.every((v, i) => v === fpBounds[i]);
63004
- });
63005
- if (match) {
63006
- if (match.value === void 0 || match.value === null) {
63007
- return { status: "unavailable" };
63008
- }
63009
- const actual = String(match.value);
63010
- return actual === expected ? { status: "matched" } : { status: "mismatched", actual };
63011
- }
63012
- return { status: "unavailable" };
63013
- }
63014
- if (rawObj.snapshot_mode === "delta" && Array.isArray(rawObj.changes?.updated)) {
63015
- const normTitle = (t) => typeof t === "string" ? t.trim().toLowerCase() : "";
63016
- const fpTitle = normTitle(fp.title);
63017
- const hit = rawObj.changes.updated.find((u) => {
63018
- if (!u || typeof u !== "object") return false;
63019
- if (verify.index !== void 0) {
63020
- return u.index === verify.index && (!fp.role || u.role === fp.role);
63021
- }
63022
- if (fp.role && u.role !== fp.role) return false;
63023
- return fpTitle ? normTitle(u.title) === fpTitle : true;
63024
- });
63025
- if (hit) {
63026
- const ch = hit.changes ?? {};
63027
- if (ch.value !== void 0 && ch.value !== null) {
63028
- const actual = String(ch.value);
63029
- return actual === expected ? { status: "matched" } : { status: "mismatched", actual };
63030
- }
63031
- }
63032
- return { status: "unavailable" };
63033
- }
63034
- return { status: "unavailable" };
63035
- }
63036
62617
  async function postActionObserve(deps, opts) {
63037
62618
  const { note } = opts;
63038
62619
  const consistency = opts.stateConsistency;
63039
- const return_state = consistency && opts.return_state === "none" ? "compact" : opts.return_state;
62620
+ const receipt = consistency?.dispatch ?? opts.dispatch ?? normalizeActionDispatchReceipt(null);
62621
+ const isError = receipt.action_sent === false ? true : void 0;
62622
+ const dispatchRecordBlock = opts.dispatchRecord && typeof opts.dispatchRecord === "object" ? textBlock(JSON.stringify(opts.dispatchRecord)) : null;
63040
62623
  if (consistency) {
63041
- toolSession(deps).markMutationDispatched(consistency.mutation);
62624
+ if (receipt.action_sent) {
62625
+ toolSession(deps).markMutationDispatched(consistency.mutation);
62626
+ } else if (receipt.dispatch_status === "not_sent") {
62627
+ toolSession(deps).consumeReferencedState(consistency.mutation);
62628
+ }
62629
+ }
62630
+ if (!receipt.action_sent) {
62631
+ opts.onEffect?.("unknown");
62632
+ return {
62633
+ content: [textBlock(note), actionReceiptBlock(receipt)],
62634
+ isError: true
62635
+ };
63042
62636
  }
63043
62637
  const hasAppRef = opts.app_ref !== void 0 && opts.app_ref !== null;
63044
- if (return_state === "none") return textResult(note);
62638
+ if (opts.return_state === "none") {
62639
+ opts.onEffect?.("unknown");
62640
+ return {
62641
+ content: dispatchRecordBlock ? [textBlock(note), dispatchRecordBlock, actionReceiptBlock(receipt)] : [textBlock(note), actionReceiptBlock(receipt)],
62642
+ isError
62643
+ };
62644
+ }
63045
62645
  if (!hasAppRef) {
62646
+ opts.onEffect?.("unknown");
63046
62647
  return {
63047
- content: [textBlock(note), unavailableEnvelope(note, "app_unknown", consistency)]
62648
+ content: [
62649
+ textBlock(note),
62650
+ actionReceiptBlock(receipt),
62651
+ textBlock(
62652
+ JSON.stringify({
62653
+ state_observation: {
62654
+ schema_version: "zcode-cua-state-observation-v1",
62655
+ status: "unavailable",
62656
+ retry_action: false,
62657
+ verification_reason: "app_unknown",
62658
+ message: "No app_ref was available for an optional post-action observation. Call get_app_state only if the next step needs UI state."
62659
+ }
62660
+ })
62661
+ )
62662
+ ],
62663
+ isError
63048
62664
  };
63049
62665
  }
63050
- const preActionState = consistency?.mutation.preActionState ?? toolSession(deps).latestStateForAppRef(opts.app_ref);
63051
- const preActionDigest = preActionState ? rawDigest(preActionState) : null;
63052
62666
  try {
63053
- const settledRaw = await captureSettledRaw(deps, opts.app_ref, opts.sleep);
63054
- const raw = await ensureActionableFullSnapshot(deps, opts.app_ref, settledRaw);
63055
- if (consistency && !isFullCaptureSnapshot(raw)) {
63056
- throw new Error("post-action state barrier requires a full actionable snapshot");
63057
- }
63058
- const mapped = await mapRawCaptureAppResult(raw, return_state, true, {
63059
- settle: true,
62667
+ const raw = await callBroker(
62668
+ deps,
62669
+ "capture_app",
62670
+ { app_ref: opts.app_ref, include_screenshot: false, force_full: true },
62671
+ { kind: "read", timeoutMs: CAPTURE_APP_TIMEOUT_MS }
62672
+ );
62673
+ const mapped = await mapRawCaptureAppResult(raw, opts.return_state, true, {
63060
62674
  session: toolSession(deps)
63061
62675
  });
63062
62676
  if (mapped === null) {
63063
- return {
63064
- content: [
63065
- textBlock(note),
63066
- failedEnvelope(note, {
63067
- reason: "transient_reobserve_failed",
63068
- suggested_action: "This looks like a transient backend/AX error, not a permanent failure: one re-observe with get_app_state is safe. Do not retry the action itself.",
63069
- warning: "The action was sent but its result could not be verified due to a transient error. A single get_app_state re-observe is safe; do not auto-retry the action.",
63070
- errorType: "UnexpectedCaptureShape"
63071
- }, consistency)
63072
- ]
63073
- };
62677
+ throw new Error("capture_app did not return a full app state");
63074
62678
  }
63075
- let noteOut = note;
63076
- let valueExtra;
63077
- if (opts.verifyValue) {
63078
- const vc = checkSetValueResult(raw, opts.verifyValue);
63079
- if (vc.status === "mismatched") {
63080
- noteOut = `Value set, but read-back shows "${vc.actual}" (requested "${opts.verifyValue.expected}"). The element may not have accepted the value (e.g. React contenteditable / read-only shadow DOM where AXSetValue mutates AX but not the DOM); consider type_text.`;
63081
- valueExtra = {
63082
- value_check: "mismatched",
63083
- expected_value: opts.verifyValue.expected,
63084
- actual_value: vc.actual
63085
- };
63086
- } else if (vc.status === "matched") {
63087
- valueExtra = { value_check: "matched" };
63088
- } else {
63089
- noteOut = "Value set, but the read-back could not confirm the written value (the settled state did not expose it \u2014 e.g. a delta snapshot without the element, or the value field is not in the AX tree). Re-observe with get_app_state to verify before relying on it.";
63090
- valueExtra = { value_check: "unavailable", expected_value: opts.verifyValue.expected };
63091
- }
63092
- }
63093
- const snapshotMode = raw !== null && typeof raw === "object" ? raw.snapshot_mode : void 0;
63094
- const postElements = raw !== null && typeof raw === "object" && Array.isArray(raw.elements) ? raw.elements : null;
63095
- const lostPreviouslyVisibleTree = postElements?.length === 0 && preActionDigest !== null && preActionDigest !== "n=0";
63096
- const effectChanged = preActionDigest === null ? null : snapshotMode === "no_change" ? false : !isFullCaptureSnapshot(raw) ? null : lostPreviouslyVisibleTree ? null : rawDigest(raw) !== preActionDigest;
63097
- const observedEffect = effectChanged === true ? "changed" : effectChanged === false ? "unchanged" : "unknown";
63098
- opts.onEffect?.(observedEffect);
63099
- const valueMatched = valueExtra?.value_check === "matched";
63100
- const targetVerificationStatus = opts.verifyValue ? valueExtra?.value_check === "matched" ? "matched" : valueExtra?.value_check === "mismatched" ? "mismatched" : "unavailable" : consistency?.dispatch.target_verification_status;
63101
- const receiptMatched = !opts.verifyValue && targetVerificationStatus === "matched";
63102
- const verificationStatus = valueMatched || receiptMatched || !consistency && effectChanged === true ? "verified" : "unavailable";
63103
- const postActionState = consistency ? toolSession(deps).latestStateForAppRef(opts.app_ref, { ignoreWindow: true }) : null;
63104
- const stateSyncStatus = consistency && postActionState && !toolSession(deps).requiresRefresh(opts.app_ref) ? "synced" : "refresh_required";
63105
- const effectExtra = effectChanged === true ? { effect_status: "changed" } : effectChanged === false ? valueMatched ? { effect_status: "unchanged" } : {
63106
- effect_status: "unchanged",
63107
- verification_reason: "no_observable_change",
63108
- warning: "The input was dispatched, but the post-action accessibility state is unchanged. Do not assume the intended UI effect occurred.",
63109
- suggested_action: "Inspect the returned state. If the target ignored app-scoped input, explicitly foreground it and use strategy=event; do not blindly repeat the same action."
63110
- } : {
63111
- effect_status: "unknown",
63112
- verification_reason: lostPreviouslyVisibleTree ? "post_action_tree_unavailable" : "pre_action_state_unavailable",
63113
- warning: lostPreviouslyVisibleTree ? "The input was dispatched, but the post-action accessibility tree was unexpectedly empty. This is not evidence that the intended UI effect occurred." : "The input was dispatched and a post-action state was captured, but no matching pre-action state was available to prove an effect.",
63114
- suggested_action: "Inspect the returned state before relying on the action result."
63115
- };
62679
+ opts.onEffect?.("unknown");
63116
62680
  return {
63117
62681
  ...mapped,
63118
62682
  content: [
63119
- textBlock(`${noteOut} (settled state below)`),
63120
- ...mapped.content,
63121
- actionOutcomeBlock(verificationStatus, true, {
63122
- ...effectExtra,
63123
- ...valueExtra,
63124
- ...consistency ? {
63125
- dispatch_status: consistency.dispatch.dispatch_status,
63126
- state_sync_status: stateSyncStatus,
63127
- pre_state_id: consistency.mutation.preActionState?.state_id,
63128
- post_state_id: postActionState?.state_id,
63129
- ax_error: consistency.dispatch.ax_error,
63130
- effect_attribution: valueMatched || receiptMatched ? "confirmed" : "not_proven",
63131
- target_verification_status: targetVerificationStatus
63132
- } : {}
63133
- })
63134
- ]
62683
+ textBlock(`${note} (state below)`),
62684
+ // 根因:长 AX tree 会被宿主从尾部截断;receipt 必须先于可选状态详情,
62685
+ // 否则 possibly_sent/retry_action=false 的防重放契约会丢失。
62686
+ actionReceiptBlock(receipt),
62687
+ ...mapped.content
62688
+ ],
62689
+ isError
63135
62690
  };
63136
62691
  } catch (e) {
63137
62692
  opts.onEffect?.("unknown");
63138
62693
  return {
63139
62694
  content: [
63140
62695
  textBlock(note),
63141
- failedEnvelope(note, classifyReobserveFailure(e), consistency)
63142
- ]
62696
+ actionReceiptBlock(receipt),
62697
+ stateUnavailableBlock(e)
62698
+ ],
62699
+ isError
63143
62700
  };
63144
62701
  }
63145
62702
  }
@@ -63201,7 +62758,7 @@ function noteObservation(raw, session = getDefaultSession()) {
63201
62758
  var listAppsTool = {
63202
62759
  name: "list_apps",
63203
62760
  title: "List Apps",
63204
- description: "List controllable applications: name, bundle_id (macOS bundle id / Windows AUMID / often empty on Linux), pid, active. On Linux/Windows prefer name or pid. Read-only.",
62761
+ description: "List running applications only: name, bundle_id (macOS bundle id / Windows AUMID / often empty on Linux), pid, active. A target missing from this list does not mean it is not installed. Do not substitute a different running application for the user-requested app. On Linux/Windows prefer name or pid. Read-only.",
63205
62762
  inputSchema: listAppsSchema,
63206
62763
  buildHandler: (deps) => async () => {
63207
62764
  try {
@@ -63221,6 +62778,8 @@ app is OS-specific:
63221
62778
  - macOS: {"bundle_id": "com.apple.TextEdit"} or {"name": "TextEdit"}.
63222
62779
  - Linux: {"name": "gedit"} or {"name": "Firefox"} (no bundle_id on Linux; use name/pid).
63223
62780
  - Windows: {"name": "Notepad"} or {"bundle_id": "Microsoft.WindowsCalculator_8wekyb3d8bbwe!App"} (AUMID for UWP).
62781
+ When bundle_id or pid is known, use that canonical identity alone; do not add a translated or guessed name.
62782
+ For a macOS app that is not running, try the original user-provided name once: copy it character-for-character into app.name, including its script, case, spaces, punctuation, and suffixes such as app. For example, use {"name":"\u7F51\u6613\u4E91\u97F3\u4E50app"}, not {"name":"\u7F51\u6613\u4E91\u97F3\u4E50"}; use {"name":"\u65E5\u5386"}, not {"name":"Calendar"}. Do not translate, localize, normalize, shorten, or remove a suffix; do not retry names, search with Bash/Finder/Spotlight, or substitute another application.
63224
62783
  If you already have a process-scoped app_ref from get_app_state/list_apps, {"pid": 123, "name": "..."}
63225
62784
  is accepted to resolve that already-running process.
63226
62785
  Browser navigation/search: pass url or urls, e.g.
@@ -63228,20 +62787,24 @@ Browser navigation/search: pass url or urls, e.g.
63228
62787
  Prefer url/urls for browsers when get_app_state has no elements or screenshot is unavailable.
63229
62788
 
63230
62789
  a11y-first: by default (activate=false) the app is NOT brought to the foreground, so
63231
- this never steals the user's focus/screen -- accessibility (get_app_state + element
63232
- targets) and app-scoped type/key(app_ref=...) work on background/covered windows. Do
62790
+ this never steals the user's focus/screen -- accessibility targets remain the primary
62791
+ background-safe path. App-scoped input may still report no observable effect; do not treat
62792
+ dispatch acceptance as proof that an attached panel or control handled it. Do
63233
62793
  NOT set activate=true just to open, observe, click element targets, or type/key with
63234
- app_ref; try those background-safe paths first. On macOS activate=true is always ignored
63235
- because the entire CUA runs in background mode. On Linux/Windows it is honored when
63236
- confirm_focus_steal=true is also set AND the server permits focus stealing (the
63237
- default for a CUA; an admin may disable it). That confirmed foreground path is the
63238
- model's acknowledgement; use it ONLY as a last resort for raw foreground key/hold_key
62794
+ app_ref; try those background-safe paths first. Set activate=true only when the operation
62795
+ genuinely requires the application foreground. The backend verifies that foreground
62796
+ postcondition on every platform and fails instead of silently falling back to background.
62797
+ The prevent_activation policy of the trusted host can still refuse activate=true before
62798
+ dispatch; the model-facing flag expresses intent and never overrides host policy.
62799
+ For an ordinary launch or application activation, omit window_id. Never guess window_id or use placeholders such as 1.
62800
+ Only for a fresh macOS open/save panel, copy the exact pid, bundle_id, and actual window_id
62801
+ returned by get_app_state with activate=true. Re-observe that surface before event key/type.
62802
+ Use foreground activation ONLY as a last resort for raw foreground key/hold_key
63239
62803
  input, or a coordinate click onto a self-drawn canvas area with no accessibility element --
63240
62804
  those are the only inputs that truly need the app frontmost. A normal left_click and all
63241
62805
  element/type/key actions are already background-safe (accessibility hit-test / AXPress) and
63242
- do NOT require activate=true, so do not set it before a coordinate or element click. Note
63243
- activate=true is enforced as a double gate (requires confirm_focus_steal=true) and is a
63244
- no-op on an already-running app (only a cold launch is brought to the foreground). The returned
62806
+ do NOT require activate=true, so do not set it before a coordinate or element click.
62807
+ activate=true also applies to an already-running exact target. The returned
63245
62808
  "active" field tells you whether the app ended up frontmost.
63246
62809
 
63247
62810
  On macOS, new_instance=true launches and verifies a separate process. Use it for a disposable
@@ -63255,20 +62818,21 @@ On Linux, keyboard input (type/key without an element target) additionally needs
63255
62818
  try {
63256
62819
  const app = args.app ?? {};
63257
62820
  const params = {
63258
- activate: args.activate,
63259
- confirm_focus_steal: args.confirm_focus_steal === true
62821
+ activate: args.activate
63260
62822
  };
63261
62823
  if (args.new_instance === true) params.new_instance = true;
63262
62824
  if (app.bundle_id !== void 0) params.bundle_id = app.bundle_id;
63263
62825
  if (app.name !== void 0) params.name = app.name;
63264
62826
  if (app.pid !== void 0) params.pid = app.pid;
62827
+ if (app.window_id !== void 0) params.window_id = app.window_id;
63265
62828
  if (app.urls !== void 0) params.urls = app.urls;
63266
62829
  if (app.url !== void 0) params.url = app.url;
63267
62830
  const requestedUrls = app.urls ?? (app.url ? [app.url] : void 0);
63268
62831
  const requestedAppRef = {
63269
62832
  ...app.pid ? { pid: app.pid } : {},
63270
62833
  ...app.bundle_id ? { bundle_id: app.bundle_id } : {},
63271
- ...app.name ? { name: app.name } : {}
62834
+ ...app.name ? { name: app.name } : {},
62835
+ ...app.window_id ? { window_id: app.window_id } : {}
63272
62836
  };
63273
62837
  if (!requestedUrls && args.activate !== true && args.new_instance !== true) {
63274
62838
  const liveApps = await callBroker(deps, "list_applications", {}, { kind: "read" });
@@ -63280,7 +62844,7 @@ On Linux, keyboard input (type/key without an element target) additionally needs
63280
62844
  if (app.bundle_id !== void 0 && String(live.bundle_id ?? "").toLocaleLowerCase() !== app.bundle_id.toLocaleLowerCase()) {
63281
62845
  return false;
63282
62846
  }
63283
- if (app.name !== void 0 && String(live.name ?? "").trim().toLocaleLowerCase() !== app.name.trim().toLocaleLowerCase()) {
62847
+ if (app.pid === void 0 && app.bundle_id === void 0 && app.name !== void 0 && String(live.name ?? "").trim().toLocaleLowerCase() !== app.name.trim().toLocaleLowerCase()) {
63284
62848
  return false;
63285
62849
  }
63286
62850
  return true;
@@ -63371,53 +62935,29 @@ var listWindowsTool = {
63371
62935
  var getAppStateTool = {
63372
62936
  name: "get_app_state",
63373
62937
  title: "Get App State",
63374
- description: 'Observe an app ONCE, then ACT on the next turn. Returns the filtered accessibility tree + a fresh state_id that element targets reference.\n\nObserve-then-act is the core loop: call this ONCE to read the current UI, then act (left_click / type / set_value / perform_action) using an element target from that state_id. Do NOT call get_app_state again on the SAME unchanged state before acting -- re-observing an identical state wastes your limited turn budget and is the leading cause of task failure. Re-observe only when (a) the server returned an element_stale error, (b) you just took an action that should have changed the UI and need to verify the result, or (c) the app/frontmost/occlusion state may have changed. When you do re-observe an identical state, the response carries a repeat_observation flag -- treat it as a signal to act now rather than observe again.\n\napp_ref = {"pid": 1234} (preferred; from list_apps), {"name": "..."} (must resolve uniquely), or {"bundle_id": "..."} (macOS bundle id / Windows AUMID). For a multi-window app, add "window_id" (integer, from list_windows or the window tuple this tool returns) to observe a SPECIFIC window, e.g. {"pid":1234,"window_id":4567}; without it the main/key window is returned (a window_id_fallback note is surfaced if the requested window could not be resolved). window_id is macOS-only and directly scopes observation, pointer events and type/key/hold_key synthetic-focus dispatch to that background window.\n\ndetail="compact" (default) returns a token-lean tree: each element as index + kind + name + capability flags (pressable/editable/has_menu/focused), which is all you need to pick an element target. detail="full" adds every field including bounds and the full `actions` list (use it when you need coordinates or a specific secondary action). Each element\'s integer `index` is valid only within this state_id.\n\nCoordinate contract: image-derived actions use integer x/y pixels from the latest returned raster; CUA binds its frame internally. app/window/element bounds=[x,y,width,height] remain diagnostic global screen points and must never be copied into a coordinate target.\n\ninclude_screenshot=false (default) keeps AX-first observations text-only so normal app control does not require or consume visual input. Set include_screenshot=true only when the task explicitly requires visual reading or frame-pixel coordinates. When present, the response emits image_ref immediately beside the image for internal integrity; do not invent or transform coordinates.\n\nIf an action fails unexpectedly or the app state looks wrong, check whether a modal dialog may be intercepting an unrelated action -- it shows up as a frontmost window here. Inspect its contents first; dismiss it only when it is NOT the intended target (press Escape, or use the dialog\'s own cancel/close control), then re-observe with get_app_state. If the dialog IS your task, read its contents before choosing an option.',
62938
+ description: 'Observe an app ONCE, then ACT on the next turn. Returns the filtered accessibility tree + a fresh state_id that element targets reference.\n\nObserve-then-act is the core loop: call this ONCE to read the current UI, then act (left_click / type / set_value / perform_action) using an element target from that state_id. Do NOT call get_app_state again on the SAME unchanged state before acting -- re-observing an identical state wastes your limited turn budget and is the leading cause of task failure. Re-observe only when (a) the server returned an element_stale error, (b) you just took an action that should have changed the UI and need to verify the result, or (c) the app/frontmost/occlusion state may have changed. This tool always requests a full snapshot from CUA; broker-internal delta/no_change replies are not model executable state.\n\napp_ref = {"pid": 1234} (preferred; from list_apps), {"name": "..."} (must resolve uniquely), or {"bundle_id": "..."} (macOS bundle id / Windows AUMID). For a multi-window app, add "window_id" (integer, from list_windows or the window tuple this tool returns) to observe a SPECIFIC window, e.g. {"pid":1234,"window_id":4567}; without it the main/key window is returned (a window_id_fallback note is surfaced if the requested window could not be resolved). macOS and Windows accept a stable window_id returned by list_windows; Linux support is backend-dependent, so never invent one. macOS also uses it for window-scoped pointer and synthetic-focus dispatch.\n\ndetail="compact" (default) returns a token-lean tree: each element as index + kind + name + capability flags (pressable/editable/has_menu/focused), which is all you need to pick an element target. detail="full" adds every field including bounds and the full `actions` list (use it when you need coordinates or a specific secondary action). Each element\'s integer `index` is valid only within this state_id.\n\nCoordinate contract: image-derived actions use integer x/y pixels from the latest returned raster; CUA binds its frame internally. app/window/element bounds=[x,y,width,height] remain diagnostic global screen points and must never be copied into a coordinate target.\n\ninclude_screenshot=false (default) keeps AX-first observations text-only so normal app control does not require or consume visual input. Set include_screenshot=true only when the task explicitly requires visual reading or frame-pixel coordinates. When present, the response emits image_ref immediately beside the image for internal integrity; do not invent or transform coordinates.\n\nIf an action fails unexpectedly or the app state looks wrong, check whether a modal dialog may be intercepting an unrelated action -- it shows up as a frontmost window here. Inspect its contents first; dismiss it only when it is NOT the intended target (press Escape, or use the dialog\'s own cancel/close control), then re-observe with get_app_state. If the dialog IS your task, read its contents before choosing an option.',
63375
62939
  inputSchema: getAppStateSchema,
63376
62940
  buildHandler: (deps) => async (input) => {
63377
62941
  const args = input;
63378
62942
  try {
63379
62943
  const session = toolSession(deps);
63380
- const params = { app_ref: args.app_ref };
62944
+ const params = { app_ref: args.app_ref, force_full: true };
63381
62945
  if (args.include_screenshot !== void 0) {
63382
62946
  params.include_screenshot = args.include_screenshot;
63383
62947
  }
63384
- const requestedWindowId = parseAppRef(args.app_ref).window_id;
63385
- if (args.detail === "full" || args.include_screenshot === true || session.requiresRefresh(args.app_ref) || !session.lastStateId() || typeof requestedWindowId === "number" && Number.isSafeInteger(requestedWindowId)) {
63386
- params.force_full = true;
63387
- }
63388
- let result = await callBroker(deps, "capture_app", params, {
62948
+ const result = await callBroker(deps, "capture_app", params, {
63389
62949
  kind: "read",
63390
62950
  timeoutMs: CAPTURE_APP_TIMEOUT_MS
63391
62951
  });
63392
- const incrementalRaw = result;
63393
- if ((incrementalRaw.snapshot_mode === "delta" || incrementalRaw.snapshot_mode === "no_change") && !session.lastStateIdFor(
63394
- incrementalRaw.app && typeof incrementalRaw.app === "object" ? incrementalRaw.app : {},
63395
- incrementalRaw.window && typeof incrementalRaw.window === "object" ? incrementalRaw.window : {}
63396
- )) {
63397
- result = await callBroker(
63398
- deps,
63399
- "capture_app",
63400
- { ...params, force_full: true },
63401
- { kind: "read", timeoutMs: CAPTURE_APP_TIMEOUT_MS }
63402
- );
63403
- }
63404
- const firstRaw = result;
63405
- if (Array.isArray(firstRaw?.elements) && firstRaw.elements.length === 0 && (firstRaw.snapshot_mode === void 0 || firstRaw.snapshot_mode === "full") && Array.isArray(firstRaw.window?.bounds) && firstRaw.window.bounds.length === 4 && session.claimEmptyTreeWarmup(
63406
- firstRaw.app ?? {},
63407
- firstRaw.window
63408
- )) {
63409
- await defaultSleepMs(80);
63410
- result = await callBroker(
63411
- deps,
63412
- "capture_app",
63413
- { ...params, force_full: true },
63414
- { kind: "read", timeoutMs: CAPTURE_APP_TIMEOUT_MS }
63415
- );
63416
- }
63417
62952
  const raw = await mapRawCaptureAppResult(result, args.detail, true, {
63418
62953
  session
63419
62954
  });
63420
62955
  if (raw) return raw;
62956
+ if (isIncrementalSnapshotResult(result)) {
62957
+ return toolError(
62958
+ "capture_app did not return a full app state. The broker returned an internal incremental snapshot, which is not model-executable; call get_app_state again."
62959
+ );
62960
+ }
63421
62961
  return mapAppStateResult(result);
63422
62962
  } catch (e) {
63423
62963
  if (shouldPropagateToWrapper(e)) throw e;
@@ -63425,10 +62965,15 @@ var getAppStateTool = {
63425
62965
  }
63426
62966
  }
63427
62967
  };
62968
+ function isIncrementalSnapshotResult(result) {
62969
+ if (!result || typeof result !== "object" || Array.isArray(result)) return false;
62970
+ const mode = result.snapshot_mode;
62971
+ return mode === "delta" || mode === "no_change";
62972
+ }
63428
62973
  var screenshotTool = {
63429
62974
  name: "screenshot",
63430
62975
  title: "Screenshot",
63431
- description: "Fallback full-display observation; prefer get_app_state. The image covers the display selected by switch_display. For a pixel action, choose x/y only by looking at the returned raster and submit them unchanged; CUA binds the frame internally. CUA owns the native projection. Metadata includes bounds=[x,y,width,height] for display identity only. screenshot_path is a diagnostic artifact only; never inspect or process it to derive action coordinates.",
62976
+ description: "Fallback full-display observation; prefer get_app_state. The image covers the display selected by switch_display. For a pixel action, choose x/y only by looking at the returned raster and submit them unchanged; CUA binds the frame internally. CUA owns the native projection. Metadata includes bounds=[x,y,width,height] for display identity only.",
63432
62977
  inputSchema: screenshotSchema,
63433
62978
  buildHandler: (deps) => async () => {
63434
62979
  try {
@@ -63489,21 +63034,14 @@ var screenshotTool = {
63489
63034
  actionable: true,
63490
63035
  non_actionable_reason: null
63491
63036
  });
63492
- const filePath = writeScreenshotArtifact(encoded.agentBytes);
63493
63037
  const content = [
63494
- // 修复原因(image-first):Anthropic 兼容网关只解析 content 开头的连续 image,
63495
- // text 一领先整张图就不进模型。raster 与紧随的 image_ref 构成原子对必须前置。
63038
+ // canonical image-first pair;consumer 只校验并预算,不再重排。
63496
63039
  {
63497
63040
  type: "image",
63498
63041
  data: encoded.agentBytes.toString("base64"),
63499
63042
  mimeType: "image/jpeg"
63500
63043
  },
63501
63044
  imageRefBlock(frameDescriptor.image_ref),
63502
- frameActionHint(),
63503
- // 根因:部分模型会优先概括首个文本块,后续即使仍有路径与图片也会误判为
63504
- // “未返回”。产物路径因此紧跟在 raster 三元组之后,仍排在说明文本之前。
63505
- ...filePath ? [textBlock(JSON.stringify({ screenshot_path: filePath }))] : [],
63506
- textBlock(screenshotCoordinateHint(agentW, agentH)),
63507
63045
  textBlock(
63508
63046
  JSON.stringify({
63509
63047
  screenshot_display: {
@@ -63562,21 +63100,7 @@ var zoomTool = {
63562
63100
  },
63563
63101
  { session: toolSession(deps) }
63564
63102
  );
63565
- const mapped = mapZoomResult(result, toolSession(deps));
63566
- const imgBlock = mapped.content.find((b) => b.type === "image");
63567
- if (imgBlock) {
63568
- const filePath = writeScreenshotArtifact(Buffer.from(imgBlock.data, "base64"));
63569
- if (filePath) {
63570
- return {
63571
- ...mapped,
63572
- // 根因:Zoom 的 diagnostic path 曾被前置到 image 之前,重新触发
63573
- // BigModel 兼容网关的 text-first 丢图。官方 raster/image_ref/hint
63574
- // 三元组必须领头;路径只用于诊断,排在其后。
63575
- content: [...mapped.content, textBlock(JSON.stringify({ screenshot_path: filePath }))]
63576
- };
63577
- }
63578
- }
63579
- return mapped;
63103
+ return mapZoomResult(result, toolSession(deps));
63580
63104
  } catch (e) {
63581
63105
  if (shouldPropagateToWrapper(e)) throw e;
63582
63106
  return toolError(e instanceof Error ? e.message : String(e));
@@ -63748,16 +63272,13 @@ function bindPointerTarget(deps, rawTarget) {
63748
63272
  frame_registry: toolSession(deps).frameRegistry
63749
63273
  });
63750
63274
  }
63751
- function resolveCoordinateFrame(deps, target) {
63275
+ function resolveCoordinateFrame(deps, target, bindingKind = frameBindingKind(target)) {
63752
63276
  const session = toolSession(deps);
63753
63277
  const { frame_id } = resolveFramePixelTarget(target, {
63754
- frame_registry: session.frameRegistry
63278
+ frame_registry: session.frameRegistry,
63279
+ binding_kind: bindingKind
63755
63280
  });
63756
- return session.frameRegistry.resolve(frame_id);
63757
- }
63758
- function frameFallbackNote(...resolutions) {
63759
- const notes = resolutions.map((resolution) => resolution.coordinate_frame_note).filter((note) => typeof note === "string" && note.length > 0);
63760
- return notes.length > 0 ? ` ${notes.join(" ")}` : "";
63281
+ return session.frameRegistry.resolveForAction(frame_id);
63761
63282
  }
63762
63283
  var POINTER_MODIFIER_ALIASES = {
63763
63284
  cmd: "cmd",
@@ -63801,6 +63322,16 @@ function pointerActionError(error51, method) {
63801
63322
  brokerDetails && typeof brokerDetails === "object" ? brokerDetails : void 0
63802
63323
  );
63803
63324
  }
63325
+ function pointerDispatchErrorResult(deps, error51, options) {
63326
+ const dispatch = actionDispatchReceiptFromError(error51);
63327
+ if (!dispatch) return pointerActionError(error51, options.method);
63328
+ return postActionObserve(deps, {
63329
+ note: options.note,
63330
+ app_ref: options.appRef,
63331
+ return_state: options.returnState,
63332
+ dispatch
63333
+ });
63334
+ }
63804
63335
  function toText2(value) {
63805
63336
  if (typeof value === "string") return value;
63806
63337
  return JSON.stringify(value);
@@ -63833,8 +63364,7 @@ async function resolveTargetForClick(deps, target) {
63833
63364
  point: resolved.point,
63834
63365
  app_ref: resolved.app_ref ?? null,
63835
63366
  fingerprint: resolved.fingerprint,
63836
- native: resolved.native,
63837
- coordinate_frame_note: resolved.coordinate_frame_note
63367
+ native: resolved.native
63838
63368
  };
63839
63369
  } catch (e) {
63840
63370
  return pointerResolveError(e);
@@ -63858,9 +63388,13 @@ async function callPointerAction(deps, method, params, targets) {
63858
63388
  try {
63859
63389
  const session = toolSession(deps);
63860
63390
  for (const rawTarget of targets) {
63391
+ const bindingKind = frameBindingKind(rawTarget);
63861
63392
  const target = parseTarget(rawTarget);
63862
63393
  if (target.type === "coordinate") {
63863
- resolveFramePixelTarget(target, { frame_registry: session.frameRegistry });
63394
+ resolveFramePixelTarget(target, {
63395
+ frame_registry: session.frameRegistry,
63396
+ binding_kind: bindingKind
63397
+ });
63864
63398
  }
63865
63399
  }
63866
63400
  } catch (error51) {
@@ -63936,10 +63470,11 @@ function verifiedPointerAppRef(appRef2, pid) {
63936
63470
  function frameActionProvenance(deps, ...targets) {
63937
63471
  const session = toolSession(deps);
63938
63472
  return targets.flatMap((rawTarget, endpointIndex) => {
63473
+ const bindingKind = frameBindingKind(rawTarget);
63939
63474
  const target = parseTarget(rawTarget);
63940
63475
  if (target.type !== "coordinate") return [];
63941
- const frame = resolveCoordinateFrame(deps, target);
63942
- const resolved = resolveTarget(target, { session });
63476
+ const frame = resolveCoordinateFrame(deps, target, bindingKind);
63477
+ const resolved = resolveTarget(rawTarget, { session });
63943
63478
  if (!resolved.point) return [];
63944
63479
  return [
63945
63480
  {
@@ -63959,6 +63494,7 @@ function frameActionProvenance(deps, ...targets) {
63959
63494
  topology_fingerprint: frame.display.topology_fingerprint
63960
63495
  },
63961
63496
  capture_windows: frame.capture_windows ?? null,
63497
+ capture_surfaces: frame.capture_surfaces ?? null,
63962
63498
  pixel: { x: target.x, y: target.y },
63963
63499
  projected_point: resolved.point,
63964
63500
  endpoint_index: endpointIndex
@@ -63987,9 +63523,10 @@ function appRefMatchesFrame(rawAppRef, frame) {
63987
63523
  }
63988
63524
  function frameScopedAppRef(deps, fallback, ...targets) {
63989
63525
  for (const rawTarget of targets) {
63526
+ const bindingKind = frameBindingKind(rawTarget);
63990
63527
  const target = parseTarget(rawTarget);
63991
63528
  if (target.type !== "coordinate") continue;
63992
- const frame = resolveCoordinateFrame(deps, target);
63529
+ const frame = resolveCoordinateFrame(deps, target, bindingKind);
63993
63530
  if (frame.app.pid === null && frame.app.bundle_id === null) continue;
63994
63531
  return {
63995
63532
  ...frame.app.pid !== null ? { pid: frame.app.pid } : {},
@@ -64003,9 +63540,10 @@ function frameDispatchIdentityError(deps, appRef2, ...targets) {
64003
63540
  if (appRef2 === void 0 || appRef2 === null) return null;
64004
63541
  try {
64005
63542
  for (const rawTarget of targets) {
63543
+ const bindingKind = frameBindingKind(rawTarget);
64006
63544
  const target = parseTarget(rawTarget);
64007
63545
  if (target.type !== "coordinate") continue;
64008
- const frame = resolveCoordinateFrame(deps, target);
63546
+ const frame = resolveCoordinateFrame(deps, target, bindingKind);
64009
63547
  if ((frame.app.pid !== null || frame.app.bundle_id !== null) && !appRefMatchesFrame(appRef2, frame)) {
64010
63548
  return toolError2(
64011
63549
  `app_ref for frame_id "${frame.frame_id}" does not match the application/window that produced the image; capture a new image from the intended app or omit app_ref. action_sent=false.`
@@ -64052,7 +63590,6 @@ async function runClick(deps, input, button, clicks) {
64052
63590
  try {
64053
63591
  const parsedClickTarget = target;
64054
63592
  const actionAppRef = frameScopedAppRef(deps, args.app_ref ?? resolved.app_ref, target);
64055
- const adaptiveDecision = strategy === "auto" ? toolSession(deps).pointerFallbackDecision(actionAppRef) : { mode: "a11y" };
64056
63593
  const elementTarget = parsedClickTarget.type === "element";
64057
63594
  const expectedPid = await resolveExpectedPid(
64058
63595
  deps,
@@ -64060,37 +63597,25 @@ async function runClick(deps, input, button, clicks) {
64060
63597
  frameProvenance.length > 0 || elementTarget && (args.app_ref === void 0 || args.app_ref === null)
64061
63598
  );
64062
63599
  const elementStateId = elementTarget ? parsedClickTarget.state_id : void 0;
64063
- if (elementTarget && toolSession(deps).requiresRefresh(actionAppRef)) {
64064
- return toolError2(
64065
- "left_click(element) refused because the previous element action still requires a full get_app_state refresh. action_sent=false."
64066
- );
64067
- }
64068
63600
  const elementMutation = elementTarget ? toolSession(deps).beginMutation(
64069
63601
  actionAppRef,
64070
63602
  typeof elementStateId === "string" ? elementStateId : void 0
64071
63603
  ) : null;
64072
63604
  let result;
64073
- let healInfo = null;
64074
63605
  let fellThroughActionUnavailable = false;
64075
- const semanticAxPress = resolved.native && resolved.fingerprint && button === "left" && clicks === 1 && !modifiers && strategy !== "event" && adaptiveDecision.mode !== "event";
63606
+ const semanticAxPress = resolved.native && resolved.fingerprint && button === "left" && clicks === 1 && !modifiers && strategy !== "event";
64076
63607
  if (semanticAxPress) {
64077
- const fingerprint = resolved.fingerprint;
64078
63608
  const native = resolved.native;
64079
63609
  const mutation = elementMutation;
64080
63610
  try {
64081
- const { result: axResult, info: axHealInfo } = await callWithElementReresolution(
63611
+ const axResult = await callPointerAction(
64082
63612
  deps,
64083
- { appRef: resolved.app_ref, fingerprint },
64084
- { native, bounds: fingerprint.bounds },
64085
- (handle) => callPointerAction(
64086
- deps,
64087
- "element_perform_action",
64088
- { native: handle.native, action: "AXPress" },
64089
- [target]
64090
- )
63613
+ "element_perform_action",
63614
+ { native, action: "AXPress" },
63615
+ [target]
64091
63616
  );
64092
63617
  return postActionObserve(deps, {
64093
- note: (axResult === null || axResult === void 0 ? "Dispatched AXPress." : toText2(axResult)) + " (semantic AXPress on the element token; no coordinate hit-test.)" + formatReresolvedNote(axHealInfo),
63618
+ note: (axResult === null || axResult === void 0 ? "Dispatched AXPress." : toText2(axResult)) + " (semantic AXPress on the element token; no coordinate hit-test.)",
64094
63619
  app_ref: actionAppRef,
64095
63620
  return_state: args.return_state,
64096
63621
  stateConsistency: {
@@ -64099,7 +63624,7 @@ async function runClick(deps, input, button, clicks) {
64099
63624
  }
64100
63625
  });
64101
63626
  } catch (e) {
64102
- const dispatch = actionDispatchReceiptFromError(e, { deps, mutation });
63627
+ const dispatch = actionDispatchReceiptFromError(e);
64103
63628
  if (dispatch) {
64104
63629
  return postActionObserve(deps, {
64105
63630
  note: "AXPress may already have reached the target element.",
@@ -64118,42 +63643,32 @@ async function runClick(deps, input, button, clicks) {
64118
63643
  fellThroughActionUnavailable = true;
64119
63644
  }
64120
63645
  }
64121
- const effStrategy = adaptiveDecision.mode === "event" ? "event" : elementTarget && (button === "left" || clicks > 1 || fellThroughActionUnavailable) ? "event" : strategy;
63646
+ const effStrategy = elementTarget && (button === "left" || clicks > 1 || fellThroughActionUnavailable) ? "event" : strategy;
64122
63647
  try {
64123
63648
  if (resolved.fingerprint && resolved.native) {
64124
- const outcome = await callWithElementReresolution(
63649
+ result = await callPointerAction(
64125
63650
  deps,
64126
- { appRef: resolved.app_ref, fingerprint: resolved.fingerprint },
63651
+ "click",
64127
63652
  {
64128
- native: resolved.native,
64129
- bounds: resolved.fingerprint.bounds
63653
+ point: elementCenter(resolved.fingerprint.bounds),
63654
+ button,
63655
+ clicks,
63656
+ modifiers,
63657
+ // P2-3: forward strategy so the broker can honor strategy=event
63658
+ // (force raw CGEvent, skip the AX hit-test path).
63659
+ strategy: effStrategy,
63660
+ // BUG-1/2: an element target is already resolved to a known app, so
63661
+ // the broker's AX hit-test owner gate is redundant — and it mis-fires
63662
+ // (ax_error) for non-pressable elements (textarea) after a semantic
63663
+ // AXPress attempt. Drop it whenever we force a raw click.
63664
+ expected_pid: expectedPid,
63665
+ app_ref: verifiedPointerAppRef(actionAppRef, expectedPid),
63666
+ ...frameProvenance.length > 0 ? { frame_provenance: frameProvenance } : {},
63667
+ expected_window_id: resolved.app_ref?.window_id,
63668
+ expected_bundle_id: resolved.app_ref?.bundle_id
64130
63669
  },
64131
- (handle) => callPointerAction(
64132
- deps,
64133
- "click",
64134
- {
64135
- point: elementCenter(handle.bounds),
64136
- button,
64137
- clicks,
64138
- modifiers,
64139
- // P2-3: forward strategy so the broker can honor strategy=event
64140
- // (force raw CGEvent, skip the AX hit-test path).
64141
- strategy: effStrategy,
64142
- // BUG-1/2: an element target is already resolved to a known app, so
64143
- // the broker's AX hit-test owner gate is redundant — and it mis-fires
64144
- // (ax_error) for non-pressable elements (textarea) after a semantic
64145
- // AXPress attempt. Drop it whenever we force a raw click.
64146
- expected_pid: expectedPid,
64147
- app_ref: verifiedPointerAppRef(actionAppRef, expectedPid),
64148
- ...frameProvenance.length > 0 ? { frame_provenance: frameProvenance } : {},
64149
- expected_window_id: resolved.app_ref?.window_id,
64150
- expected_bundle_id: resolved.app_ref?.bundle_id
64151
- },
64152
- [target]
64153
- )
63670
+ [target]
64154
63671
  );
64155
- result = outcome.result;
64156
- healInfo = outcome.info;
64157
63672
  } else {
64158
63673
  result = await callPointerAction(
64159
63674
  deps,
@@ -64174,17 +63689,19 @@ async function runClick(deps, input, button, clicks) {
64174
63689
  );
64175
63690
  }
64176
63691
  } catch (error51) {
64177
- const dispatch = elementMutation ? actionDispatchReceiptFromError(error51, { deps, mutation: elementMutation }) : null;
64178
- if (!dispatch || !elementMutation) throw error51;
63692
+ const dispatch = actionDispatchReceiptFromError(error51);
63693
+ if (!dispatch) throw error51;
64179
63694
  return postActionObserve(deps, {
64180
- note: "Element click may already have reached the target window.",
63695
+ note: elementMutation ? "Element click may already have reached the target window." : "Coordinate click may already have reached the target window.",
64181
63696
  app_ref: actionAppRef,
64182
63697
  return_state: args.return_state,
64183
- stateConsistency: { mutation: elementMutation, dispatch }
63698
+ ...elementMutation ? { stateConsistency: { mutation: elementMutation, dispatch } } : { dispatch }
64184
63699
  });
64185
63700
  }
63701
+ if (elementMutation) {
63702
+ }
64186
63703
  return postActionObserve(deps, {
64187
- note: toText2(result) + formatReresolvedNote(healInfo) + frameFallbackNote(resolved) + (adaptiveDecision.mode === "event" ? ` (adaptive raw fallback: ${adaptiveDecision.reason}; foreground ownership was verified.)` : ""),
63704
+ note: toText2(result),
64188
63705
  app_ref: resolvedActionAppRef(result, actionAppRef),
64189
63706
  return_state: args.return_state,
64190
63707
  ...elementMutation ? {
@@ -64276,7 +63793,6 @@ var scrollTool = {
64276
63793
  let point;
64277
63794
  let targetAppRef;
64278
63795
  let targetIsElement = false;
64279
- let scrollFallbackNote = "";
64280
63796
  try {
64281
63797
  const resolved = resolveTarget(target, {
64282
63798
  session: toolSession(deps)
@@ -64289,7 +63805,6 @@ var scrollTool = {
64289
63805
  point = resolved.point;
64290
63806
  targetAppRef = resolved.app_ref;
64291
63807
  targetIsElement = resolved.isElement;
64292
- scrollFallbackNote = frameFallbackNote(resolved);
64293
63808
  if (strategy === "a11y") {
64294
63809
  return toolError2(
64295
63810
  "scroll has no accessibility actuation; strategy=a11y requires an accessibility operation (AX/UIA/AT-SPI), but scrolling is implemented as raw pointer input. Use strategy=event (background/window-scoped on macOS) or keyboard navigation against a focused element."
@@ -64320,12 +63835,17 @@ var scrollTool = {
64320
63835
  [target]
64321
63836
  );
64322
63837
  return postActionObserve(deps, {
64323
- note: scrollNote(applied, requested) + scrollFallbackNote,
63838
+ note: scrollNote(applied, requested),
64324
63839
  app_ref: resolvedActionAppRef(result, scopedAppRef),
64325
63840
  return_state: args.return_state
64326
63841
  });
64327
63842
  } catch (e) {
64328
- return pointerActionError(e, "scroll");
63843
+ return pointerDispatchErrorResult(deps, e, {
63844
+ method: "scroll",
63845
+ note: "Scroll may already have reached the target window.",
63846
+ appRef: args.app_ref ?? targetAppRef,
63847
+ returnState: args.return_state ?? "none"
63848
+ });
64329
63849
  }
64330
63850
  }
64331
63851
  };
@@ -64337,6 +63857,7 @@ var leftClickDragTool = {
64337
63857
  inputSchema: leftClickDragSchema,
64338
63858
  buildHandler: (deps) => async (input) => {
64339
63859
  const args = input;
63860
+ let dispatchAppRef = args.app_ref;
64340
63861
  try {
64341
63862
  const fromTarget = bindPointerTarget(deps, args.from_target);
64342
63863
  const toTarget = bindPointerTarget(deps, args.to);
@@ -64387,6 +63908,7 @@ var leftClickDragTool = {
64387
63908
  fromTarget,
64388
63909
  toTarget
64389
63910
  );
63911
+ dispatchAppRef = scopedAppRef;
64390
63912
  const result = await callPointerAction(
64391
63913
  deps,
64392
63914
  "drag",
@@ -64400,12 +63922,17 @@ var leftClickDragTool = {
64400
63922
  [fromTarget, toTarget]
64401
63923
  );
64402
63924
  return postActionObserve(deps, {
64403
- note: DRAG_NOTE + frameFallbackNote(start, end),
63925
+ note: DRAG_NOTE,
64404
63926
  app_ref: resolvedActionAppRef(result, scopedAppRef),
64405
63927
  return_state: args.return_state
64406
63928
  });
64407
63929
  } catch (e) {
64408
- return pointerActionError(e, "drag");
63930
+ return pointerDispatchErrorResult(deps, e, {
63931
+ method: "drag",
63932
+ note: "Drag may already have reached the target window.",
63933
+ appRef: dispatchAppRef,
63934
+ returnState: args.return_state ?? "none"
63935
+ });
64409
63936
  }
64410
63937
  }
64411
63938
  };
@@ -64417,6 +63944,7 @@ var mouseMoveTool = {
64417
63944
  inputSchema: mouseMoveSchema,
64418
63945
  buildHandler: (deps) => async (input) => {
64419
63946
  const args = input;
63947
+ let dispatchAppRef = args.app_ref;
64420
63948
  try {
64421
63949
  const coordinate = bindPointerTarget(deps, args.coordinate);
64422
63950
  const identityError = frameDispatchIdentityError(deps, args.app_ref, coordinate);
@@ -64433,6 +63961,7 @@ var mouseMoveTool = {
64433
63961
  args.app_ref ?? resolved.app_ref,
64434
63962
  coordinate
64435
63963
  );
63964
+ dispatchAppRef = scopedAppRef;
64436
63965
  const expectedPid = await resolveExpectedPid(
64437
63966
  deps,
64438
63967
  scopedAppRef,
@@ -64454,16 +63983,18 @@ var mouseMoveTool = {
64454
63983
  },
64455
63984
  [coordinate]
64456
63985
  );
64457
- if (!args.return_state || args.return_state === "none") {
64458
- return textResult2(MOVE_NOTE + frameFallbackNote(resolved));
64459
- }
64460
63986
  return postActionObserve(deps, {
64461
- note: MOVE_NOTE + frameFallbackNote(resolved),
63987
+ note: MOVE_NOTE,
64462
63988
  app_ref: resolvedActionAppRef(result, scopedAppRef),
64463
- return_state: args.return_state
63989
+ return_state: args.return_state ?? "none"
64464
63990
  });
64465
63991
  } catch (e) {
64466
- return pointerActionError(e, "move_to");
63992
+ return pointerDispatchErrorResult(deps, e, {
63993
+ method: "move_to",
63994
+ note: "Mouse move may already have reached the target window.",
63995
+ appRef: dispatchAppRef,
63996
+ returnState: args.return_state ?? "none"
63997
+ });
64467
63998
  }
64468
63999
  }
64469
64000
  };
@@ -64471,7 +64002,7 @@ var MOUSE_DOWN_NOTE = "Mouse button pressed at resolved element or scoped coordi
64471
64002
  var leftMouseDownTool = {
64472
64003
  name: "left_mouse_down",
64473
64004
  title: "Left Mouse Down",
64474
- description: 'Press and hold the left mouse button at an element or frame-bound coordinate. ADVANCED/RAW and requires an element or frame-bound coordinate target. Coordinate targets are bound to the current raster internally, so the press is scoped to an observed app/window. On macOS the pair is window-scoped and leaves the real cursor/frontmost app intact. A left_mouse_down + left_mouse_up pair is a click, so independently verify the target before releasing. return_state defaults to compact and re-observes the held app; the matching left_mouse_up reuses that stored app scope. Release with left_mouse_up. Examples: left_mouse_down(target={"type":"element","state_id":"s-1","index":4}); left_mouse_down(target={"type":"coordinate","x":100,"y":100}). ' + SKILL_REF,
64005
+ description: 'Press and hold the left mouse button at an element or frame-bound coordinate. ADVANCED/RAW and requires an element or frame-bound coordinate target. Coordinate targets are bound to the current raster internally, so the press is scoped to an observed app/window. On macOS the pair is window-scoped and leaves the real cursor/frontmost app intact. A left_mouse_down + left_mouse_up pair is a click, so independently verify the target before releasing. return_state defaults to none; request compact/full only when fresh UI state is needed. The matching left_mouse_up reuses the stored app scope. Release with left_mouse_up. Examples: left_mouse_down(target={"type":"element","state_id":"s-1","index":4}); left_mouse_down(target={"type":"coordinate","x":100,"y":100}). ' + SKILL_REF,
64475
64006
  inputSchema: leftMouseDownSchema,
64476
64007
  buildHandler: (deps) => async (input) => {
64477
64008
  const args = input;
@@ -64480,7 +64011,6 @@ var leftMouseDownTool = {
64480
64011
  let targetIsElement = false;
64481
64012
  let frameProvenance = [];
64482
64013
  let target;
64483
- let mouseDownFallbackNote = "";
64484
64014
  try {
64485
64015
  target = bindPointerTarget(deps, args.target);
64486
64016
  const identityError = frameDispatchIdentityError(deps, args.app_ref, target);
@@ -64497,7 +64027,6 @@ var leftMouseDownTool = {
64497
64027
  point = resolved.point;
64498
64028
  targetAppRef = resolved.app_ref;
64499
64029
  targetIsElement = resolved.isElement;
64500
- mouseDownFallbackNote = frameFallbackNote(resolved);
64501
64030
  } catch (e) {
64502
64031
  return pointerResolveError(e);
64503
64032
  }
@@ -64542,9 +64071,9 @@ var leftMouseDownTool = {
64542
64071
  deps.inputState.appRef = observedAppRef;
64543
64072
  }
64544
64073
  return postActionObserve(deps, {
64545
- note: MOUSE_DOWN_NOTE + mouseDownFallbackNote,
64074
+ note: MOUSE_DOWN_NOTE,
64546
64075
  app_ref: observedAppRef,
64547
- return_state: args.return_state ?? "compact"
64076
+ return_state: args.return_state ?? "none"
64548
64077
  });
64549
64078
  } catch (e) {
64550
64079
  const deliveryState = e !== null && typeof e === "object" && "details" in e && e.details?.request_delivery_state;
@@ -64555,7 +64084,12 @@ var leftMouseDownTool = {
64555
64084
  deps.inputState.appRef = void 0;
64556
64085
  }
64557
64086
  }
64558
- return pointerActionError(e, "mouse_down");
64087
+ return pointerDispatchErrorResult(deps, e, {
64088
+ method: "mouse_down",
64089
+ note: "Mouse down may already have reached the target window.",
64090
+ appRef: deps.inputState?.appRef ?? args.app_ref ?? targetAppRef,
64091
+ returnState: args.return_state ?? "none"
64092
+ });
64559
64093
  }
64560
64094
  }
64561
64095
  };
@@ -64563,10 +64097,11 @@ var MOUSE_UP_NOTE = "Mouse button released.";
64563
64097
  var leftMouseUpTool = {
64564
64098
  name: "left_mouse_up",
64565
64099
  title: "Left Mouse Up",
64566
- description: "Release the left mouse button previously pressed by this MCP session. CLEANUP RELEASE ONLY: it refuses when this session has not successfully called left_mouse_down, so an accidental call cannot release the user's own mouse press. return_state defaults to compact and re-observes the app scope remembered by the matching left_mouse_down; use none only when another observer supplies the result evidence. Example: left_mouse_up(). " + SKILL_REF,
64100
+ description: "Release the left mouse button previously pressed by this MCP session. CLEANUP RELEASE ONLY: it refuses when this session has not successfully called left_mouse_down, so an accidental call cannot release the user's own mouse press. return_state defaults to none; request compact/full only when fresh UI state is needed. The app scope is remembered from the matching left_mouse_down. Example: left_mouse_up(). " + SKILL_REF,
64567
64101
  inputSchema: leftMouseUpSchema,
64568
64102
  buildHandler: (deps) => async (input) => {
64569
64103
  const args = input;
64104
+ const heldAppRef = deps.inputState?.appRef;
64570
64105
  try {
64571
64106
  const sessionKey = toolSessionKey(deps);
64572
64107
  const ownership = deps.pointerHoldGuard?.ownerState(sessionKey);
@@ -64580,7 +64115,6 @@ var leftMouseUpTool = {
64580
64115
  "mouse_up refused: another MCP session holds the left mouse button. This request did not send a release; action_sent=false. Wait for that session to call mouse_up or stop_computer_control."
64581
64116
  );
64582
64117
  }
64583
- const heldAppRef = deps.inputState?.appRef;
64584
64118
  await callBroker(
64585
64119
  deps,
64586
64120
  "mouse_up",
@@ -64597,11 +64131,15 @@ var leftMouseUpTool = {
64597
64131
  return postActionObserve(deps, {
64598
64132
  note: MOUSE_UP_NOTE,
64599
64133
  app_ref: heldAppRef,
64600
- return_state: args.return_state ?? "compact"
64134
+ return_state: args.return_state ?? "none"
64601
64135
  });
64602
64136
  } catch (e) {
64603
- if (shouldPropagateToWrapper(e)) throw e;
64604
- return toolError2(e instanceof Error ? e.message : String(e));
64137
+ return pointerDispatchErrorResult(deps, e, {
64138
+ method: "mouse_up",
64139
+ note: "Mouse up may already have reached the target window.",
64140
+ appRef: heldAppRef,
64141
+ returnState: args.return_state ?? "none"
64142
+ });
64605
64143
  }
64606
64144
  }
64607
64145
  };
@@ -64746,6 +64284,36 @@ function textRangeSplitsUtf16SurrogatePair(text, range) {
64746
64284
  const [start, length] = range;
64747
64285
  return splitsUtf16SurrogatePair(text, start) || splitsUtf16SurrogatePair(text, start + length);
64748
64286
  }
64287
+ var CUA_REQUEST_ACCESS_STATUS_META_KEY = "zcode.cua/request-access-status-v1";
64288
+ var cuaRequestAccessStatusSchema = external_exports.object({
64289
+ schemaVersion: external_exports.literal(1),
64290
+ platform: external_exports.literal("darwin"),
64291
+ grantOwner: external_exports.string().trim().min(1).max(512),
64292
+ accessibility: external_exports.enum(["granted", "stale", "denied"]),
64293
+ screenRecording: external_exports.enum(["granted", "denied", "unknown"])
64294
+ }).strict();
64295
+ function readCuaRequestAccessStatus(platform, report) {
64296
+ if (platform !== "darwin") return void 0;
64297
+ const parsed = cuaRequestAccessStatusSchema.safeParse({
64298
+ schemaVersion: 1,
64299
+ platform,
64300
+ grantOwner: report.grant_owner,
64301
+ accessibility: report.accessibility,
64302
+ screenRecording: report.screen_recording
64303
+ });
64304
+ return parsed.success ? parsed.data : void 0;
64305
+ }
64306
+ function attachCuaRequestAccessStatusMeta(result, platform, report) {
64307
+ const status = readCuaRequestAccessStatus(platform, report);
64308
+ if (!status) return result;
64309
+ return {
64310
+ ...result,
64311
+ _meta: {
64312
+ ...result._meta,
64313
+ [CUA_REQUEST_ACCESS_STATUS_META_KEY]: status
64314
+ }
64315
+ };
64316
+ }
64749
64317
  function explicitElementTarget(target) {
64750
64318
  const parsed = parseTarget(target);
64751
64319
  return parsed.type === "element" ? parsed : null;
@@ -64781,6 +64349,8 @@ async function verifyCompoundKeyboardAppRef(deps, appRef2, method) {
64781
64349
  );
64782
64350
  } catch (error51) {
64783
64351
  if (isBrokerUnavailableException(error51)) throw error51;
64352
+ const details = brokerErrorDetails(error51);
64353
+ if (details?.reason === "surface_replaced") throw error51;
64784
64354
  const detail = error51 instanceof Error ? error51.message : String(error51);
64785
64355
  throw new Error(
64786
64356
  `${method}: compound app_ref could not be bound to one live application before keyboard dispatch (${detail}). action_sent=false.`
@@ -64790,8 +64360,23 @@ async function verifyCompoundKeyboardAppRef(deps, appRef2, method) {
64790
64360
  const live = app && typeof app === "object" && !Array.isArray(app) ? app : null;
64791
64361
  const window2 = captured && typeof captured === "object" && !Array.isArray(captured) ? captured.window : null;
64792
64362
  const liveWindow = window2 && typeof window2 === "object" && !Array.isArray(window2) ? window2 : null;
64793
- const mismatch = !live || typeof expected.pid === "number" && live.pid !== expected.pid || typeof expected.bundle_id === "string" && (typeof live.bundle_id !== "string" || live.bundle_id.trim().toLowerCase() !== expected.bundle_id.trim().toLowerCase()) || typeof expected.name === "string" && (typeof live.name !== "string" || live.name.trim().toLowerCase() !== expected.name.trim().toLowerCase()) || typeof expected.window_id === "number" && (!liveWindow || liveWindow.window_id !== expected.window_id);
64794
- if (mismatch) {
64363
+ const appMismatch = !live || typeof expected.pid === "number" && live.pid !== expected.pid || typeof expected.bundle_id === "string" && (typeof live.bundle_id !== "string" || live.bundle_id.trim().toLowerCase() !== expected.bundle_id.trim().toLowerCase()) || typeof expected.name === "string" && (typeof live.name !== "string" || live.name.trim().toLowerCase() !== expected.name.trim().toLowerCase());
64364
+ const windowMismatch = typeof expected.window_id === "number" && (!liveWindow || liveWindow.window_id !== expected.window_id);
64365
+ if (!appMismatch && windowMismatch) {
64366
+ throw Object.assign(
64367
+ new Error(
64368
+ `${method}: surface_replaced; app_ref.window_id ${String(expected.window_id)} does not identify the current attached surface. Call get_app_state and use the new actual_window_id. action_sent=false.`
64369
+ ),
64370
+ {
64371
+ details: {
64372
+ action_sent: false,
64373
+ reason: "surface_replaced",
64374
+ recovery: "Call get_app_state and use the new attached surface identity; do not reuse the old window_id."
64375
+ }
64376
+ }
64377
+ );
64378
+ }
64379
+ if (appMismatch) {
64795
64380
  throw new Error(
64796
64381
  `${method}: pid, bundle_id, name, and window_id in app_ref must identify the same live application/window. Call list_apps/list_windows and reuse one row's identity fields. action_sent=false.`
64797
64382
  );
@@ -64811,6 +64396,16 @@ function brokerErrorDetails(error51) {
64811
64396
  function toolError3(text, details) {
64812
64397
  return details === void 0 ? { isError: true, content: [textBlock3(text)] } : { isError: true, content: [textBlock3(text)], structuredContent: { ...details } };
64813
64398
  }
64399
+ function keyboardDispatchErrorResult(deps, error51, options) {
64400
+ const dispatch = actionDispatchReceiptFromError(error51);
64401
+ if (!dispatch) return null;
64402
+ return postActionObserve(deps, {
64403
+ note: options.note,
64404
+ app_ref: options.appRef,
64405
+ return_state: options.returnState,
64406
+ dispatch
64407
+ });
64408
+ }
64814
64409
  function appRefHasIdentity(appRef2) {
64815
64410
  if (appRef2 === null || appRef2 === void 0 || typeof appRef2 !== "object") {
64816
64411
  return false;
@@ -64848,12 +64443,24 @@ async function typeViaAppOrFocus(deps, text, returnState, appRef2, strategy) {
64848
64443
  const params = { text };
64849
64444
  if (hasRef) params.app_ref = processScopedKeyboardAppRef(appRef2);
64850
64445
  if (strategy === "event") params.strategy = strategy;
64851
- await callBroker(deps, method, params, { kind: "action" });
64852
- return postActionObserve(deps, {
64853
- note: typedTextNote(text),
64854
- app_ref: appRef2,
64855
- return_state: returnState
64856
- });
64446
+ try {
64447
+ const result = await callBroker(deps, method, params, { kind: "action" });
64448
+ return postActionObserve(deps, {
64449
+ note: typedTextNote(text),
64450
+ app_ref: appRef2,
64451
+ return_state: returnState,
64452
+ dispatch: normalizeActionDispatchReceipt(result),
64453
+ dispatchRecord: result && typeof result === "object" && !Array.isArray(result) ? result : null
64454
+ });
64455
+ } catch (error51) {
64456
+ const result = keyboardDispatchErrorResult(deps, error51, {
64457
+ note: "Typing may already have reached the target app.",
64458
+ appRef: appRef2,
64459
+ returnState
64460
+ });
64461
+ if (result) return result;
64462
+ throw error51;
64463
+ }
64857
64464
  }
64858
64465
  async function coordinateHitTestPreflight(deps, target, resolved) {
64859
64466
  if (resolved.native || resolved.kind !== "coordinate") {
@@ -64874,7 +64481,7 @@ async function coordinateHitTestPreflight(deps, target, resolved) {
64874
64481
  var typeTool = {
64875
64482
  name: "type",
64876
64483
  title: "Type",
64877
- description: 'Type text into an editable element, a target app, or the current focus.\n\nPrefer element targets: `target` is an element target ({"type":"element","state_id","index"}); a coordinate target is accepted and first hit-tested through accessibility to the element owning that point (an empty or non-actuable point is refused with action_sent=false). With an editable element the default (strategy=auto/a11y) sets the field\'s value via accessibility -- no focus move, no global keystrokes -- so it works on a background/non-frontmost app and never steals focus; it REPLACES the field\'s contents (select_text first, or strategy=event, to insert). With `app_ref` and no element, this is app-scoped input: macOS posts to the target window through a synthetic-focus SkyLight session (background-safe, including Chromium); app_ref.window_id is preserved and verified immediately before dispatch. On Linux and Windows (neither has pid-targeted keyboard) the app MUST be frontmost or the call is refused -- prefer an editable element target when not frontmost. On macOS strategy=event explicitly activates and re-verifies app_ref.window_id, then sends one foreground event; it is refused when focus stealing is disabled. Without target/app_ref, a11y backends refuse because raw foreground text can hit the user\'s current-focus app; only non-a11y fallback backends use targetless current-focus typing.\nExample: type(text="hello", target={"type":"element","state_id":"s-1","index":1}).\n' + SKILL_REF2,
64484
+ description: 'Type text into an editable element, a target app, or the current focus.\n\nPrefer element targets: `target` is an element target ({"type":"element","state_id","index"}); a coordinate target is accepted and first hit-tested through accessibility to the element owning that point (an empty or non-actuable point is refused with action_sent=false). With an editable element the default (strategy=auto/a11y) sets the field\'s value via accessibility -- no focus move, no global keystrokes -- so it works on a background/non-frontmost app and never steals focus; it REPLACES the field\'s contents (select_text first, or strategy=event, to insert). With `app_ref` and no element, this is app-scoped input: macOS posts to the target window through a synthetic-focus SkyLight session (background-safe, including Chromium); app_ref.window_id is preserved and verified immediately before dispatch. On Linux and Windows (neither has pid-targeted keyboard) the app MUST be frontmost or the call is refused -- prefer an editable element target when not frontmost. On macOS strategy=event requires the app and exact app_ref.window_id already frontmost and focused; it never activates implicitly. For open/save panels, first call confirmed open_application and re-observe. After Cmd+Shift+G, observe by pid/bundle without the old panel window_id, then type against the fresh attached_dialog actual_window_id. Without target/app_ref, a11y backends refuse because raw foreground text can hit the user\'s current-focus app; only non-a11y fallback backends use targetless current-focus typing.\nExample: type(text="hello", target={"type":"element","state_id":"s-1","index":1}).\n' + SKILL_REF2,
64878
64485
  inputSchema: typeSchema,
64879
64486
  buildHandler: (deps) => async (input) => {
64880
64487
  const args = input;
@@ -64899,56 +64506,36 @@ var typeTool = {
64899
64506
  const nativeAppRef = hit.native ? hit.app_ref : r.resolved.app_ref ?? null;
64900
64507
  if (nativeToken && args.strategy !== "event") {
64901
64508
  const fingerprint = r.resolved.fingerprint ?? null;
64902
- if (toolSession(deps).requiresRefresh(nativeAppRef)) {
64903
- return toolError3(
64904
- "type(target) refused because the previous element action still requires a full get_app_state refresh. action_sent=false."
64905
- );
64906
- }
64907
64509
  const targetStateId = explicitElementStateId(args.target);
64908
64510
  const mutation = toolSession(deps).beginMutation(
64909
64511
  nativeAppRef,
64910
- typeof targetStateId === "string" ? targetStateId : void 0
64512
+ typeof targetStateId === "string" ? targetStateId : null
64911
64513
  );
64912
64514
  if (fingerprint) {
64913
64515
  try {
64914
- const { result, info } = await callWithElementReresolution(
64516
+ const result = await callBroker(
64915
64517
  deps,
64916
- { appRef: r.resolved.app_ref, fingerprint },
64917
- { native: nativeToken, bounds: fingerprint.bounds },
64918
- (handle) => callBroker(
64919
- deps,
64920
- "element_set_value",
64921
- { native: handle.native, value: args.text },
64922
- { kind: "action" }
64923
- )
64518
+ "element_set_value",
64519
+ { native: nativeToken, value: args.text },
64520
+ { kind: "action" }
64924
64521
  );
64925
64522
  return postActionObserve(deps, {
64926
- note: (args.text.length === 0 ? "Cleared the target element value by typing an empty string." : typedTextNote(args.text)) + formatReresolvedNote(info),
64523
+ note: args.text.length === 0 ? "Cleared the target element value by typing an empty string." : typedTextNote(args.text),
64927
64524
  app_ref: r.resolved.app_ref ?? null,
64928
64525
  return_state: args.return_state,
64929
64526
  stateConsistency: {
64930
64527
  mutation,
64931
64528
  dispatch: normalizeActionDispatchReceipt(result)
64932
- },
64933
- verifyValue: {
64934
- expected: args.text,
64935
- fingerprint,
64936
- index: explicitElementTarget(args.target)?.index
64937
64529
  }
64938
64530
  });
64939
64531
  } catch (error51) {
64940
- const dispatch = actionDispatchReceiptFromError(error51, { deps, mutation });
64532
+ const dispatch = actionDispatchReceiptFromError(error51);
64941
64533
  if (!dispatch) throw error51;
64942
64534
  return postActionObserve(deps, {
64943
64535
  note: "Type element value may already have reached the app.",
64944
64536
  app_ref: r.resolved.app_ref ?? null,
64945
64537
  return_state: args.return_state,
64946
- stateConsistency: { mutation, dispatch },
64947
- verifyValue: {
64948
- expected: args.text,
64949
- fingerprint,
64950
- index: explicitElementTarget(args.target)?.index
64951
- }
64538
+ stateConsistency: { mutation, dispatch }
64952
64539
  });
64953
64540
  }
64954
64541
  }
@@ -64969,7 +64556,7 @@ var typeTool = {
64969
64556
  }
64970
64557
  });
64971
64558
  } catch (error51) {
64972
- const dispatch = actionDispatchReceiptFromError(error51, { deps, mutation });
64559
+ const dispatch = actionDispatchReceiptFromError(error51);
64973
64560
  if (!dispatch) throw error51;
64974
64561
  return postActionObserve(deps, {
64975
64562
  note: "Type element value may already have reached the app.",
@@ -65024,16 +64611,11 @@ Example: set_value(target={"type":"element","state_id":"s-1","index":0}, value="
65024
64611
  "target did not resolve to a native element token; pass an element target from get_app_state."
65025
64612
  );
65026
64613
  }
65027
- if (toolSession(deps).requiresRefresh(nativeAppRef)) {
65028
- return toolError3(
65029
- "set_value refused because the previous element action still requires a full get_app_state refresh. action_sent=false."
65030
- );
65031
- }
65032
64614
  const observedFingerprint = r.resolved.fingerprint ?? null;
65033
64615
  const targetStateId = explicitElementStateId(args.target);
65034
64616
  const mutation = toolSession(deps).beginMutation(
65035
64617
  nativeAppRef,
65036
- typeof targetStateId === "string" ? targetStateId : void 0
64618
+ typeof targetStateId === "string" ? targetStateId : null
65037
64619
  );
65038
64620
  if (!observedFingerprint) {
65039
64621
  try {
@@ -65053,7 +64635,7 @@ Example: set_value(target={"type":"element","state_id":"s-1","index":0}, value="
65053
64635
  }
65054
64636
  });
65055
64637
  } catch (e) {
65056
- const dispatch = actionDispatchReceiptFromError(e, { deps, mutation });
64638
+ const dispatch = actionDispatchReceiptFromError(e);
65057
64639
  if (dispatch) {
65058
64640
  return postActionObserve(deps, {
65059
64641
  note: "Set value request may already have reached the app.",
@@ -65066,53 +64648,34 @@ Example: set_value(target={"type":"element","state_id":"s-1","index":0}, value="
65066
64648
  return toolError3(e instanceof Error ? e.message : String(e));
65067
64649
  }
65068
64650
  }
65069
- const fingerprint = r.resolved.fingerprint;
65070
64651
  try {
65071
- const { result, info } = await callWithElementReresolution(
64652
+ const result = await callBroker(
65072
64653
  deps,
65073
- { appRef: r.resolved.app_ref, fingerprint },
65074
- { native: nativeToken, bounds: fingerprint.bounds },
65075
- (handle) => callBroker(
65076
- deps,
65077
- "element_set_value",
65078
- {
65079
- native: handle.native,
65080
- value: args.value,
65081
- strategy: args.strategy
65082
- },
65083
- { kind: "action" }
65084
- )
64654
+ "element_set_value",
64655
+ {
64656
+ native: nativeToken,
64657
+ value: args.value,
64658
+ strategy: args.strategy
64659
+ },
64660
+ { kind: "action" }
65085
64661
  );
65086
64662
  return postActionObserve(deps, {
65087
- note: `Set value request dispatched.${formatReresolvedNote(info)}`,
64663
+ note: "Set value request dispatched.",
65088
64664
  app_ref: r.resolved.app_ref ?? null,
65089
64665
  return_state: args.return_state,
65090
64666
  stateConsistency: {
65091
64667
  mutation,
65092
64668
  dispatch: normalizeActionDispatchReceipt(result)
65093
- },
65094
- verifyValue: {
65095
- expected: String(args.value),
65096
- fingerprint,
65097
- // Carry the target's observe-time index so the delta-mode read-back
65098
- // matches the exact element (delta entries have no bounds); without
65099
- // it, duplicate same-role/title controls could be misread.
65100
- index: explicitElementTarget(args.target)?.index
65101
64669
  }
65102
64670
  });
65103
64671
  } catch (e) {
65104
- const dispatch = actionDispatchReceiptFromError(e, { deps, mutation });
64672
+ const dispatch = actionDispatchReceiptFromError(e);
65105
64673
  if (dispatch) {
65106
64674
  return postActionObserve(deps, {
65107
64675
  note: "Set value request may already have reached the app.",
65108
64676
  app_ref: r.resolved.app_ref ?? null,
65109
64677
  return_state: args.return_state,
65110
- stateConsistency: { mutation, dispatch },
65111
- verifyValue: {
65112
- expected: String(args.value),
65113
- fingerprint,
65114
- index: explicitElementTarget(args.target)?.index
65115
- }
64678
+ stateConsistency: { mutation, dispatch }
65116
64679
  });
65117
64680
  }
65118
64681
  if (shouldPropagateToWrapper(e)) throw e;
@@ -65157,16 +64720,11 @@ var selectTextTool = {
65157
64720
  "target did not resolve to a native element token; pass an element target from get_app_state."
65158
64721
  );
65159
64722
  }
65160
- if (toolSession(deps).requiresRefresh(nativeAppRef)) {
65161
- return toolError3(
65162
- "select_text refused because the previous element action still requires a full get_app_state refresh. action_sent=false."
65163
- );
65164
- }
65165
64723
  const observedFingerprint = r.resolved.fingerprint ?? null;
65166
64724
  const selectTargetStateId = explicitElementStateId(args.target);
65167
64725
  const mutation = toolSession(deps).beginMutation(
65168
64726
  nativeAppRef,
65169
- typeof selectTargetStateId === "string" ? selectTargetStateId : void 0
64727
+ typeof selectTargetStateId === "string" ? selectTargetStateId : null
65170
64728
  );
65171
64729
  pendingMutation = mutation;
65172
64730
  pendingAppRef = nativeAppRef;
@@ -65205,22 +64763,17 @@ var selectTextTool = {
65205
64763
  );
65206
64764
  }
65207
64765
  }
65208
- const { result, info } = await callWithElementReresolution(
64766
+ const result = await callBroker(
65209
64767
  deps,
65210
- { appRef: r.resolved.app_ref, fingerprint },
65211
- { native: nativeToken, bounds: fingerprint.bounds },
65212
- (handle) => callBroker(
65213
- deps,
65214
- "element_select_text",
65215
- { native: handle.native, ...textRangeParam },
65216
- { kind: "action" }
65217
- )
64768
+ "element_select_text",
64769
+ { native: nativeToken, ...textRangeParam },
64770
+ { kind: "action" }
65218
64771
  );
65219
64772
  const range = textRangeParam.text_range;
65220
64773
  const isCaret = !range || range[1] === 0;
65221
64774
  const note = isCaret ? `Caret placed at ${range ? range[0] : "current position"} (no text selected).` : `Text selected.`;
65222
64775
  return postActionObserve(deps, {
65223
- note: `${note}${formatReresolvedNote(info)}`,
64776
+ note,
65224
64777
  app_ref: r.resolved.app_ref ?? null,
65225
64778
  return_state: args.return_state,
65226
64779
  stateConsistency: {
@@ -65229,7 +64782,7 @@ var selectTextTool = {
65229
64782
  }
65230
64783
  });
65231
64784
  } catch (e) {
65232
- const dispatch = pendingMutation ? actionDispatchReceiptFromError(e, { deps, mutation: pendingMutation }) : actionDispatchReceiptFromError(e);
64785
+ const dispatch = actionDispatchReceiptFromError(e);
65233
64786
  if (dispatch && pendingMutation) {
65234
64787
  return postActionObserve(deps, {
65235
64788
  note: "Text-selection request may already have reached the app.",
@@ -65249,7 +64802,7 @@ var selectTextTool = {
65249
64802
  var keyTool = {
65250
64803
  name: "key",
65251
64804
  title: "Key",
65252
- description: 'Press a non-text key or explicit chord (Return, Escape, Tab, cmd+a, arrows). Not for typing ordinary text -- use type(app_ref=..., text=...) for that. Negative repeat is refused, repeat=0 is a no-op, and positive values are clamped to 1..100. With `app_ref`, sends an app-scoped chord (macOS binds it to the verified CGWindowID through synthetic focus); on Linux and Windows (neither has pid-targeted keyboard) the app MUST be frontmost or the call is refused -- prefer an element target / perform_action when the app is not frontmost. Without `app_ref` this is a FOREGROUND-ONLY raw fallback: a11y backends refuse it because a GLOBAL key would reach the user\'s frontmost app; only non-a11y fallback backends use targetless current-focus keys. Modifiers are OS-specific: macOS cmd/shift/ctrl/alt; Linux ctrl/shift/alt/super; Windows ctrl/shift/alt/win. Use ctrl (not cmd) for shortcuts on Linux/Windows.\nOn macOS strategy="event" explicitly activates and re-verifies app_ref.window_id before foreground raw delivery; auto keeps the synthetic-focus background route. A focused submit button + Enter is auto-routed through the element action path, no strategy needed.\nExample: key(text="return", app_ref={"pid":1}).\n' + SKILL_REF2,
64805
+ description: 'Press a non-text key or explicit chord (Return, Escape, Tab, cmd+a, arrows). Not for typing ordinary text -- use type(app_ref=..., text=...) for that. Negative repeat is refused, repeat=0 is a no-op, and positive values are clamped to 1..100. With `app_ref`, sends an app-scoped chord (macOS binds it to the verified CGWindowID through synthetic focus); on Linux and Windows (neither has pid-targeted keyboard) the app MUST be frontmost or the call is refused -- prefer an element target / perform_action when the app is not frontmost. Without `app_ref` this is a FOREGROUND-ONLY raw fallback: a11y backends refuse it because a GLOBAL key would reach the user\'s frontmost app; only non-a11y fallback backends use targetless current-focus keys. Modifiers are OS-specific: macOS cmd/shift/ctrl/alt; Linux ctrl/shift/alt/super; Windows ctrl/shift/alt/win. Use ctrl (not cmd) for shortcuts on Linux/Windows.\nOn macOS strategy="event" requires an already-frontmost, freshly verified app_ref.window_id; it never activates implicitly. File panels require confirmed open_application followed by a fresh observation; after Cmd+Shift+G, omit the old panel window_id once to discover and pin the focused attached_dialog. auto keeps the synthetic-focus background route. A focused submit button + Enter is auto-routed through the element action path, no strategy needed.\nExample: key(text="return", app_ref={"pid":1}).\n' + SKILL_REF2,
65253
64806
  inputSchema: keySchema,
65254
64807
  buildHandler: (deps) => async (input) => {
65255
64808
  const args = input;
@@ -65285,16 +64838,28 @@ var keyTool = {
65285
64838
  const params = { text: args.text };
65286
64839
  if (hasAppRef) params.app_ref = processScopedKeyboardAppRef(args.app_ref);
65287
64840
  if (args.strategy) params.strategy = args.strategy;
64841
+ const note = clamped.clamped ? `Key pressed ${clamped.value} time(s) (requested ${requested}, clamped to 1..100).` : `Key pressed ${clamped.value} time(s).`;
64842
+ let dispatch;
64843
+ let dispatchRecord = null;
65288
64844
  for (let i = 0; i < clamped.value; i++) {
65289
- await callBroker(deps, method, params, { kind: "action" });
64845
+ const result = await callBroker(deps, method, params, { kind: "action" });
64846
+ dispatch = normalizeActionDispatchReceipt(result);
64847
+ dispatchRecord = result && typeof result === "object" && !Array.isArray(result) ? result : null;
65290
64848
  }
65291
- const note = clamped.clamped ? `Key pressed ${clamped.value} time(s) (requested ${requested}, clamped to 1..100).` : `Key pressed ${clamped.value} time(s).`;
65292
64849
  return postActionObserve(deps, {
65293
64850
  note,
65294
64851
  app_ref: args.app_ref,
65295
- return_state: args.return_state
64852
+ return_state: args.return_state,
64853
+ ...dispatch ? { dispatch } : {},
64854
+ dispatchRecord
65296
64855
  });
65297
64856
  } catch (e) {
64857
+ const receiptResult = keyboardDispatchErrorResult(deps, e, {
64858
+ note: "Key press may already have reached the target app.",
64859
+ appRef: args.app_ref,
64860
+ returnState: args.return_state
64861
+ });
64862
+ if (receiptResult) return receiptResult;
65298
64863
  if (shouldPropagateToWrapper(e)) throw e;
65299
64864
  return toolError3(
65300
64865
  e instanceof Error ? e.message : String(e),
@@ -65306,7 +64871,7 @@ var keyTool = {
65306
64871
  var holdKeyTool = {
65307
64872
  name: "hold_key",
65308
64873
  title: "Hold Key",
65309
- description: 'Hold a key or chord for a duration (clamped to 0..30 seconds). With `app_ref`, holds an app-scoped chord (macOS binds it to the verified background CGWindowID); on Linux and Windows (neither has window-targeted keyboard) the app MUST be frontmost or the call is refused -- prefer an element target when the app is not frontmost. Without `app_ref` this is a FOREGROUND-ONLY raw fallback: a11y backends refuse a targetless hold because a GLOBAL key would reach the user\'s frontmost app. On macOS, auto keeps the verified background window route; strategy="event" explicitly activates and re-verifies app_ref.window_id before foreground raw delivery.\nExample: hold_key(text="shift", duration=1.0, app_ref={"pid":1}).\n' + SKILL_REF2,
64874
+ description: 'Hold a key or chord for a duration (clamped to 0..30 seconds). With `app_ref`, holds an app-scoped chord (macOS binds it to the verified background CGWindowID); on Linux and Windows (neither has window-targeted keyboard) the app MUST be frontmost or the call is refused -- prefer an element target when the app is not frontmost. Without `app_ref` this is a FOREGROUND-ONLY raw fallback: a11y backends refuse a targetless hold because a GLOBAL key would reach the user\'s frontmost app. On macOS, auto keeps the verified background window route; strategy="event" requires an already-frontmost, fresh app_ref.window_id and never activates implicitly.\nExample: hold_key(text="shift", duration=1.0, app_ref={"pid":1}).\n' + SKILL_REF2,
65310
64875
  inputSchema: holdKeySchema,
65311
64876
  buildHandler: (deps) => async (input) => {
65312
64877
  const args = input;
@@ -65387,6 +64952,12 @@ var holdKeyTool = {
65387
64952
  return_state: args.return_state
65388
64953
  });
65389
64954
  } catch (e) {
64955
+ const receiptResult = keyboardDispatchErrorResult(deps, e, {
64956
+ note: "Key hold may already have reached the target app.",
64957
+ appRef: args.app_ref,
64958
+ returnState: args.return_state
64959
+ });
64960
+ if (receiptResult) return receiptResult;
65390
64961
  if (shouldPropagateToWrapper(e)) throw e;
65391
64962
  return toolError3(
65392
64963
  e instanceof Error ? e.message : String(e),
@@ -65426,16 +64997,11 @@ var performActionTool = {
65426
64997
  "target did not resolve to a native element token; pass an element target from get_app_state."
65427
64998
  );
65428
64999
  }
65429
- if (toolSession(deps).requiresRefresh(nativeAppRef)) {
65430
- return toolError3(
65431
- "perform_action refused because the previous element action still requires a full get_app_state refresh. action_sent=false."
65432
- );
65433
- }
65434
65000
  const observedFingerprint = r.resolved.fingerprint ?? null;
65435
65001
  const performTargetStateId = explicitElementStateId(args.target);
65436
65002
  const mutation = toolSession(deps).beginMutation(
65437
65003
  nativeAppRef,
65438
- typeof performTargetStateId === "string" ? performTargetStateId : void 0
65004
+ typeof performTargetStateId === "string" ? performTargetStateId : null
65439
65005
  );
65440
65006
  if (!observedFingerprint) {
65441
65007
  try {
@@ -65455,7 +65021,7 @@ var performActionTool = {
65455
65021
  }
65456
65022
  });
65457
65023
  } catch (e) {
65458
- const dispatch = actionDispatchReceiptFromError(e, { deps, mutation });
65024
+ const dispatch = actionDispatchReceiptFromError(e);
65459
65025
  if (dispatch) {
65460
65026
  return postActionObserve(deps, {
65461
65027
  note: `Dispatch of ${args.action} may already have reached the app.`,
@@ -65485,20 +65051,14 @@ var performActionTool = {
65485
65051
  }
65486
65052
  }
65487
65053
  try {
65488
- const fingerprint = r.resolved.fingerprint;
65489
- const { result, info } = await callWithElementReresolution(
65054
+ const result = await callBroker(
65490
65055
  deps,
65491
- { appRef: r.resolved.app_ref, fingerprint },
65492
- { native: nativeToken, bounds: fingerprint.bounds },
65493
- (handle) => callBroker(
65494
- deps,
65495
- "element_perform_action",
65496
- { native: handle.native, action },
65497
- { kind: "action" }
65498
- )
65056
+ "element_perform_action",
65057
+ { native: nativeToken, action },
65058
+ { kind: "action" }
65499
65059
  );
65500
65060
  return postActionObserve(deps, {
65501
- note: `Dispatched ${action}.` + (action !== args.action ? ` (normalized from ${args.action})` : "") + formatReresolvedNote(info),
65061
+ note: `Dispatched ${action}.` + (action !== args.action ? ` (normalized from ${args.action})` : ""),
65502
65062
  app_ref: r.resolved.app_ref ?? null,
65503
65063
  return_state: args.return_state,
65504
65064
  stateConsistency: {
@@ -65507,7 +65067,7 @@ var performActionTool = {
65507
65067
  }
65508
65068
  });
65509
65069
  } catch (e) {
65510
- const dispatch = actionDispatchReceiptFromError(e, { deps, mutation });
65070
+ const dispatch = actionDispatchReceiptFromError(e);
65511
65071
  if (dispatch) {
65512
65072
  return postActionObserve(deps, {
65513
65073
  note: `Dispatch of ${action} may already have reached the app.`,
@@ -65562,7 +65122,11 @@ var requestAccessTool = {
65562
65122
  },
65563
65123
  guard: toolKillSwitch(deps).status()
65564
65124
  };
65565
- return textResult3(toText3(guardPayload));
65125
+ return attachCuaRequestAccessStatusMeta(
65126
+ textResult3(toText3(guardPayload)),
65127
+ brokerInfo.platform,
65128
+ result
65129
+ );
65566
65130
  } catch (e) {
65567
65131
  if (shouldPropagateToWrapper(e)) throw e;
65568
65132
  return toolError3(
@@ -65843,8 +65407,6 @@ var REQUEST_CONTEXT_META_KEY = "com.zcode/request-context";
65843
65407
  var SUBAGENT_RUNTIME_SCOPE = "subagent";
65844
65408
  var SUBAGENT_COMPUTER_USE_UNAVAILABLE_CODE = "SUBAGENT_COMPUTER_USE_UNAVAILABLE";
65845
65409
  var SUBAGENT_COMPUTER_USE_UNAVAILABLE_MESSAGE = "Computer Use is not available in subagent";
65846
- var CUA_PERMISSION_REQUIRED_CODE = "CUA_PERMISSION_REQUIRED";
65847
- var CUA_PERMISSION_REQUIRED_GUIDANCE = "Computer Use is blocked by a missing macOS permission (Accessibility and/or Screen Recording). Ask the user to grant it via Settings \u2192 Computer Use, which opens the system grant flow. Retry this same tool call after the user confirms the grant.";
65848
65410
  function withKillSwitchPreflight(name, handler, deps) {
65849
65411
  return (input, extra) => runWithTargetAppDisplayContext(async () => {
65850
65412
  const requestContext = extra?._meta?.[REQUEST_CONTEXT_META_KEY];
@@ -65867,19 +65429,6 @@ function withKillSwitchPreflight(name, handler, deps) {
65867
65429
  try {
65868
65430
  return await handler(input);
65869
65431
  } catch (e) {
65870
- if (isMacTccPermissionRefusal(e)) {
65871
- const refused = e;
65872
- const axError = typeof refused.details?.ax_error === "string" ? refused.details.ax_error : void 0;
65873
- return {
65874
- isError: true,
65875
- content: [{ type: "text", text: CUA_PERMISSION_REQUIRED_GUIDANCE }],
65876
- structuredContent: {
65877
- code: CUA_PERMISSION_REQUIRED_CODE,
65878
- broker_code: refused.code,
65879
- ...axError ? { ax_error: axError } : {}
65880
- }
65881
- };
65882
- }
65883
65432
  if (isBrokerUnavailableException(e)) {
65884
65433
  const payload = notReadyResultForException(name, e);
65885
65434
  return { content: [{ type: "text", text: JSON.stringify(payload) }] };
@@ -65936,15 +65485,15 @@ function registerAllTools(server, deps) {
65936
65485
  }
65937
65486
  var SERVER_NAME = "zcode-cua";
65938
65487
  var SERVER_VERSION = (() => {
65939
- if ("0.5.10".trim().length > 0) {
65940
- return "0.5.10";
65488
+ if ("0.5.12".trim().length > 0) {
65489
+ return "0.5.12";
65941
65490
  }
65942
65491
  try {
65943
65492
  const require2 = createRequire2(import.meta.url);
65944
65493
  return require2("../../package.json").version;
65945
65494
  } catch (e) {
65946
65495
  console.warn(
65947
- `[zcode-cua] Could not read version from package.json (${e instanceof Error ? e.message : e}); falling back to "0.0.0-unknown".`
65496
+ `[Computer Use] Could not read version from package.json (${e instanceof Error ? e.message : e}); falling back to "0.0.0-unknown".`
65948
65497
  );
65949
65498
  return "0.0.0-unknown";
65950
65499
  }
@@ -67548,7 +67097,7 @@ async function startStreamableHttpServer(options) {
67548
67097
  const httpAuthToken = options.httpAuthToken?.trim();
67549
67098
  if (!LOOPBACK_HOSTS.has(host)) {
67550
67099
  console.error(
67551
- `[zcode-cua] DANGER: allowing plaintext streamable-http on ${host}; ${httpAuthToken ? "bearer credentials and control traffic can be intercepted" : "any reachable client can control this machine"}`
67100
+ `[Computer Use] DANGER: allowing plaintext streamable-http on ${host}; ${httpAuthToken ? "bearer credentials and control traffic can be intercepted" : "any reachable client can control this machine"}`
67552
67101
  );
67553
67102
  }
67554
67103
  const app = createMcpExpressApp({ host });
@@ -67606,7 +67155,7 @@ async function startStreamableHttpServer(options) {
67606
67155
  const closeSessionInBackground = (sessionId, trigger) => {
67607
67156
  void closeSession(sessionId).catch((error51) => {
67608
67157
  console.error(
67609
- `[zcode-cua] HTTP ${trigger} cleanup failed: ${errorMessage(error51)}`
67158
+ `[Computer Use] HTTP ${trigger} cleanup failed: ${errorMessage(error51)}`
67610
67159
  );
67611
67160
  });
67612
67161
  };
@@ -67747,7 +67296,7 @@ async function startStreamableHttpServer(options) {
67747
67296
  jsonError(res, 500, error51 instanceof Error ? error51.message : "Internal server error");
67748
67297
  } else {
67749
67298
  console.error(
67750
- `[zcode-cua] HTTP request cleanup failed after response: ${errorMessage(error51)}`
67299
+ `[Computer Use] HTTP request cleanup failed after response: ${errorMessage(error51)}`
67751
67300
  );
67752
67301
  }
67753
67302
  } finally {
@@ -68223,6 +67772,7 @@ var MAX_SAMPLE_DIMENSION = 64;
68223
67772
  var MAX_SAMPLED_PIXELS = MAX_SAMPLE_DIMENSION * MAX_SAMPLE_DIMENSION;
68224
67773
  var MAX_BLANK_SAMPLE_DIMENSION = 64;
68225
67774
  var MAX_BLANK_SAMPLED_PIXELS = MAX_BLANK_SAMPLE_DIMENSION * MAX_BLANK_SAMPLE_DIMENSION;
67775
+ var APPLICATION_SEARCH_MAX_BYTES = 1024 * 1024;
68226
67776
  var CLIPBOARD_MAX_BUFFER = 16 * 1024 * 1024;
68227
67777
  var MAX_PNG_BYTES = 128 * 1024 * 1024;
68228
67778
  var CONTROL_TYPE_TO_KIND = Object.freeze({
@@ -68276,7 +67826,7 @@ var VALUE_SET_KINDS2 = /* @__PURE__ */ new Set([
68276
67826
  "slider",
68277
67827
  "stepper"
68278
67828
  ]);
68279
- var IN_TREE_ADDON_REL = join4("build", "Release", "ax_native.node");
67829
+ var IN_TREE_ADDON_REL = join3("build", "Release", "ax_native.node");
68280
67830
  var PIP_SESSION_HIDDEN_GROUP_ID = "__zcode_pip_no_active_session_v2__";
68281
67831
  var identifierSchema = external_exports.string().trim().min(1).max(255).refine((value) => !value.includes("\0"), "identifier cannot contain NUL").refine(
68282
67832
  (value) => value !== PIP_SESSION_HIDDEN_GROUP_ID,
@@ -68368,11 +67918,11 @@ var INTRANET_PROBE_SERVICE_PORT = 3850;
68368
67918
  var INTRANET_PROBE_SERVICE_PATH = "/api/intranet/probe";
68369
67919
  var INTRANET_PROBE_SERVICE_URL = `http://${INTRANET_MACHINE_HOST}:${INTRANET_PROBE_SERVICE_PORT}${INTRANET_PROBE_SERVICE_PATH}`;
68370
67920
  var DEFAULT_HELPER_MAX_DOWNLOAD_BYTES = 200 * 1024 * 1024;
68371
- var DEV_BROKER_CREDENTIALS_DIR = join5("computer-use", "run");
67921
+ var DEV_BROKER_CREDENTIALS_DIR = join4("computer-use", "run");
68372
67922
  var CUA_PERMISSION_REFRESH_TERM_GRACE_MS = CUA_PERMISSION_BROKER_GRACEFUL_STOP_TIMEOUT_MS + 2e3;
68373
67923
  var PROJECT_CONFIG_FILES = [
68374
67924
  "zcode.json",
68375
- join6(".zcode", "config.json")
67925
+ join5(".zcode", "config.json")
68376
67926
  ];
68377
67927
  var BROKER_REFRESH_MARKER_ENV = ZCODE_CUA_BROKER_REFRESH_MARKER_ENV_KEY;
68378
67928
  var HTTP_AUTH_TOKEN_ENV = "ZCODE_CUA_HTTP_AUTH_TOKEN";
@@ -68403,7 +67953,7 @@ async function main(opts = {}) {
68403
67953
  httpAuthToken: opts.httpAuthToken,
68404
67954
  allowUnauthenticatedRemoteHttp: opts.allowUnauthenticatedRemoteHttp
68405
67955
  });
68406
- console.error(`[zcode-cua] Streamable HTTP MCP listening at ${running.url}`);
67956
+ console.error(`[Computer Use] Streamable HTTP MCP listening at ${running.url}`);
68407
67957
  await new Promise((resolve22) => {
68408
67958
  let closing = false;
68409
67959
  const shutdown = () => {
@@ -68411,7 +67961,7 @@ async function main(opts = {}) {
68411
67961
  closing = true;
68412
67962
  void running.close().catch((error51) => {
68413
67963
  console.error(
68414
- `[zcode-cua] HTTP shutdown failed: ${error51 instanceof Error ? error51.message : String(error51)}`
67964
+ `[Computer Use] HTTP shutdown failed: ${error51 instanceof Error ? error51.message : String(error51)}`
68415
67965
  );
68416
67966
  process.exitCode = 1;
68417
67967
  }).finally(resolve22);
@@ -68439,7 +67989,7 @@ async function main(opts = {}) {
68439
67989
  await runStdioCleanup();
68440
67990
  } catch (error51) {
68441
67991
  console.error(
68442
- `[zcode-cua] stdin close input cleanup failed: ${error51 instanceof Error ? error51.message : String(error51)}`
67992
+ `[Computer Use] stdin close input cleanup failed: ${error51 instanceof Error ? error51.message : String(error51)}`
68443
67993
  );
68444
67994
  process.exitCode = 1;
68445
67995
  throw error51;
@@ -68449,7 +67999,7 @@ async function main(opts = {}) {
68449
67999
  const stdioShutdown = () => {
68450
68000
  void runStdioCleanup().catch((error51) => {
68451
68001
  console.error(
68452
- `[zcode-cua] signal shutdown input cleanup failed: ${error51 instanceof Error ? error51.message : String(error51)}`
68002
+ `[Computer Use] signal shutdown input cleanup failed: ${error51 instanceof Error ? error51.message : String(error51)}`
68453
68003
  );
68454
68004
  process.exitCode = 1;
68455
68005
  }).finally(() => process.exit());