noracu 0.3.1 → 0.3.3

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.
@@ -50,7 +50,7 @@ _MIRROR_NOT_RUNNING_LINE = (
50
50
  )
51
51
  _MIRROR_STATE_UNKNOWN_LINE = (
52
52
  "mirror_state_unknown: could not tell whether iPhone Mirroring is live — "
53
- "nothing was sent; retry, or call phone_status"
53
+ "nothing was sent; call phone_status, and if it stays unknown, stop and tell the person"
54
54
  )
55
55
 
56
56
  # One line, one exit code for every capture failure. The pixels a check
@@ -179,8 +179,8 @@ def _refuse_off_screen(x: float, y: float, *, measure: bool) -> int | None:
179
179
  x0, y0, x1, y1 = rect
180
180
  print(
181
181
  f"out_of_screen: ({_num(x)},{_num(y)}) is on the iPhone Mirroring window's margin, not on the "
182
- f"phone screen (x {x0:.3f}-{x1:.3f}, y {y0:.3f}-{y1:.3f}): a click there goes to the window's "
183
- f"own controls or nowhere; nothing was sent",
182
+ f"phone screen (x {x0:.3f}-{x1:.3f}, y {y0:.3f}-{y1:.3f}) — call phone_screenshot and pass 0-1 "
183
+ f"coordinates inside the screen; nothing was sent",
184
184
  file=sys.stderr,
185
185
  )
186
186
  return 2
@@ -200,8 +200,7 @@ def _refuse_off_screen(x: float, y: float, *, measure: bool) -> int | None:
200
200
  print(
201
201
  f"out_of_screen: ({_num(x)},{_num(y)}) may be on the iPhone Mirroring window's margin: the phone "
202
202
  f"screen's edges are not known ({_EDGES_UNTRUSTED}), and while they are not, a point outside x {x0:.3f}-{x1:.3f}, "
203
- f"y {y0:.3f}-{y1:.3f} is not sent — the strip above the screen holds the window's own controls; "
204
- f"nothing was sent. Move the pointer off the top of the mirror window and try again, or aim further inside",
203
+ f"y {y0:.3f}-{y1:.3f} is not sent — call phone_screenshot and aim further inside; nothing was sent",
205
204
  file=sys.stderr,
206
205
  )
207
206
  return 2
@@ -210,7 +209,7 @@ def _refuse_off_screen(x: float, y: float, *, measure: bool) -> int | None:
210
209
  def _mirror_not_live(overlay: dict) -> int:
211
210
  label = overlay.get("overlay") or "overlay shown"
212
211
  print(
213
- f"mirror_not_live: {label} — call phone_launch (or imctl resume) first",
212
+ f"mirror_not_live: {label} — call phone_launch first",
214
213
  file=sys.stderr,
215
214
  )
216
215
  return 3
@@ -481,8 +480,8 @@ def _refuse_collapsed(asked) -> int:
481
480
  print(
482
481
  f"out_of_screen: the swipe from ({_num(asked[0])},{_num(asked[1])}) to ({_num(asked[2])},{_num(asked[3])}) "
483
482
  f"starts or ends on the iPhone Mirroring window's margin, or where it may be: with its points moved "
484
- f"onto the phone screen it would be shorter than a swipe (under about {_MIN_MOVED_SWIPE_PT:g} pt) — a press, "
485
- f"not a swipe; nothing was sent",
483
+ f"onto the phone screen it would be shorter than a swipe (under about {_MIN_MOVED_SWIPE_PT:g} pt): a press, "
484
+ f"not a swipe — call phone_screenshot and start and end it inside the screen; nothing was sent",
486
485
  file=sys.stderr,
487
486
  )
488
487
  return 2
@@ -672,7 +671,7 @@ def _cmd_type(args) -> int:
672
671
  print(
673
672
  "type_not_confirmed: the paste did not show on screen within the 2.5s "
674
673
  f"confirmation window{watched} — {advice}; the clipboard still holds the "
675
- "typed text and your previous clipboard was not restored",
674
+ "typed text and the person's previous clipboard was not restored",
676
675
  file=sys.stderr,
677
676
  )
678
677
  return 4
@@ -870,7 +869,7 @@ def _open_and_report(args) -> int:
870
869
  if os.environ.get("NORACU_TOPHIT_LABELS", "").strip():
871
870
  print(f"app not found: {args.app!r} (Spotlight showed no Top Hit labelled "
872
871
  f"{', '.join(repr(x) for x in gestures.TOP_HIT_LABELS)} — no app by that "
873
- f"name, or NORACU_TOPHIT_LABELS does not match your iPhone's label){stuck}")
872
+ f"name, or NORACU_TOPHIT_LABELS does not match the iPhone's label){stuck}")
874
873
  else:
875
874
  # 2026-11-08: the top-field Spotlight shows no Top Hit header at all; there the
876
875
  # evidence is the field completing the name with "— Open"
@@ -926,6 +925,12 @@ def _open_and_report(args) -> int:
926
925
  else "the clipboard was put back unless something else had copied meanwhile")
927
926
  + "; retry phone_open", file=sys.stderr)
928
927
  return 6
928
+ if result == "not_cleared":
929
+ print(f"open_not_confirmed: Spotlight's search field still showed earlier text after it was "
930
+ f"cleared twice (empty, it reads \"Search or Ask\" or \"Search\" — in English only), so {args.app!r} "
931
+ f"was not typed after that text and nothing was tapped; {home_note}; retry phone_open",
932
+ file=sys.stderr)
933
+ return 4
929
934
  if result == "clipboard_changed":
930
935
  print(f"open_not_confirmed: another app or device changed the clipboard before ⌘V, so "
931
936
  f"{args.app!r} was not pasted or tapped and the new clipboard was left as it is; "
@@ -971,17 +976,16 @@ def _cmd_launch(_args) -> int:
971
976
  if is_setup_screen():
972
977
  # A welcome / setup screen is the user's to finish; nothing was clicked.
973
978
  print(
974
- "mirror_setup_required: iPhone Mirroring is showing a setup or welcome "
975
- "screen (its window is not phone-shaped) — finish it in the iPhone "
976
- "Mirroring window yourself (noracu never clicks through setup screens), "
979
+ "mirror_setup_required: iPhone Mirroring shows a setup or welcome screen — stop "
980
+ "and tell the person to finish it (noracu never clicks through setup screens), "
977
981
  "then call phone_launch again",
978
982
  file=sys.stderr,
979
983
  )
980
984
  return 3
981
985
  print(
982
- "mirror_not_live: iPhone Mirroring is not live yet — if it shows a paused "
983
- "notice, lock the iPhone and keep it near the Mac; if it is reconnecting, wait "
984
- "a few seconds and check phone_status; then call phone_launch again",
986
+ "mirror_not_live: iPhone Mirroring is not live yet — paused: tell the person to lock "
987
+ "the iPhone and keep it near the Mac; reconnecting: call phone_status in a few "
988
+ "seconds; then phone_launch again",
985
989
  file=sys.stderr,
986
990
  )
987
991
  return 3
@@ -1130,7 +1134,7 @@ def _run(args) -> int:
1130
1134
  return args.func(args)
1131
1135
  except input.KeyboardLayoutMismatch as exc:
1132
1136
  # raised before any event was posted or the clipboard was written
1133
- print(f"keyboard_layout: {exc}", file=sys.stderr)
1137
+ print(f"keyboard_layout: {exc} — stop and tell the person; do not retry", file=sys.stderr)
1134
1138
  return 2
1135
1139
  except input.FocusLost as exc:
1136
1140
  # The frontmost check failed right before an event — either
@@ -698,6 +698,71 @@ def _top_field_lines(hits):
698
698
  return lines
699
699
 
700
700
 
701
+ # The search field's own line in the top-field layout: read at ny 0.12–0.13 on the device (2026-11-08,
702
+ # 2026-11-21). After a clear only a line at that height is taken for the field, and its placeholder for
703
+ # an empty one; lines higher up in the zone are not the field.
704
+ FIELD_LINE_MIN_NY = 0.09
705
+ # The empty field's placeholder, English as the "Open" completion is: "Search or Ask" in the top-field
706
+ # layout, "Search" in the bottom-field one (read there as "Q Search": the magnifier glyph in front taken
707
+ # for a Q, as in the field echo above). "Search" counts in either.
708
+ FIELD_PLACEHOLDERS = ("search or ask", "search")
709
+ _MAGNIFIER_Q = re.compile(r"^q[\s.,:;·•]*")
710
+
711
+
712
+ def _placeholder(text):
713
+ """``text`` (_norm_label'ed) is the empty field's placeholder, with or without the magnifier glyph
714
+ read as "Q" in front of it."""
715
+ return text in FIELD_PLACEHOLDERS or _MAGNIFIER_Q.sub("", text, count=1) in FIELD_PLACEHOLDERS
716
+
717
+
718
+ def _field_left(hits):
719
+ """What Spotlight's search field still shows after a clear: [] when the placeholder is read in
720
+ the field of either layout — at the top field's height, or in the bottom field
721
+ (ny >= SEARCH_FIELD_NY) — or when no line is at the top field's height (no evidence either way);
722
+ otherwise the queries of the lines there. The bottom-field layout can have a section header at
723
+ that height (its Top Hit header was measured at ny ≈ 0.14), so its own field decides there."""
724
+ if any(h.ny >= SEARCH_FIELD_NY and _placeholder(_norm_label(h.text)) for h in hits):
725
+ return []
726
+ lines = [query for ny, query, _a in _top_field_lines(hits) if ny >= FIELD_LINE_MIN_NY]
727
+ if any(_placeholder(q) for q in lines):
728
+ return []
729
+ return [q for q in lines if q]
730
+
731
+
732
+ def clear_search_field(*, clear=None, read_screen=None, sleep=time.sleep, settle_s: float = 0.3) -> bool:
733
+ """Empty Spotlight's search field, and check that it is empty.
734
+
735
+ Cmd+A + Delete (``clear``, default inp.clear_text) does not always empty it: on the device
736
+ (2026-11-21, once in eight tries) the previous query stayed, and the name typed next went in
737
+ after it. So the field is read after the clear. Its placeholder ("Search or Ask", or "Search"), or
738
+ no line at the field's height, counts as empty; any other text there gets one more clear, and text still
739
+ there after that one means the field could not be emptied: False. A read that fails is no
740
+ evidence (True, as before this check). The caller has made sure Spotlight is open
741
+ (open_spotlight_checked), so the clear can only land in its field — a second one as well.
742
+ ``read_screen`` defaults to vision.read_screen.
743
+ """
744
+ if clear is None:
745
+ clear = inp.clear_text
746
+ if read_screen is None:
747
+ read_screen = vision.read_screen
748
+
749
+ def left():
750
+ try:
751
+ return _field_left(read_screen())
752
+ except Exception as exc:
753
+ if not verify.is_capture_error(exc):
754
+ raise
755
+ return []
756
+
757
+ clear()
758
+ sleep(settle_s)
759
+ if not left():
760
+ return True
761
+ clear()
762
+ sleep(settle_s)
763
+ return not left()
764
+
765
+
701
766
  def _top_field_for(hits, name):
702
767
  """(ny, action) of the top search field when it shows ``name`` (exactly, after _norm_label),
703
768
  with or without a completion; None otherwise."""
@@ -810,7 +875,9 @@ def open_app(name: str, *, spotlight_open: bool = False,
810
875
 
811
876
  The search field is cleared (Cmd+A + Delete) before typing: iOS
812
877
  keeps the previous Spotlight query, so the new name would be
813
- appended to it and no result row would match. Results are
878
+ appended to it and no result row would match. The field is read
879
+ back after the clear (clear_search_field): text that two clears
880
+ leave in it ends the open before typing (not_cleared). Results are
814
881
  then read up to twice (find_app_hit) because they can lag the
815
882
  keystrokes — or, when type_text did not see the paste arrive, once a
816
883
  second for up to OPEN_LATE_PASTE_S: once the search field shows
@@ -865,7 +932,10 @@ def open_app(name: str, *, spotlight_open: bool = False,
865
932
  off and nothing was tapped; Spotlight is left as it is — going Home
866
933
  would pull the mirror forward again); "clipboard_changed" (another app or
867
934
  device wrote the clipboard before ⌘V: nothing was pasted or tapped, the
868
- new clipboard is left alone; back on the Home Screen); or
935
+ new clipboard is left alone; back on the Home Screen); "not_cleared"
936
+ (the search field still showed text after two clears, so the name
937
+ was not typed after it and nothing was tapped; back on the Home
938
+ Screen); or
869
939
  "spotlight_unavailable" (Spotlight could not be opened; nothing was
870
940
  typed or tapped).
871
941
 
@@ -893,7 +963,10 @@ def open_app(name: str, *, spotlight_open: bool = False,
893
963
  return ok
894
964
 
895
965
  if clear_text is None:
896
- clear_text = inp.clear_text
966
+ # the field is read after the clear (clear_search_field), with the screen reader as it is
967
+ # here — not the wrapper below, whose reads count as evidence that the paste arrived
968
+ def clear_text(_read=read_screen):
969
+ return clear_search_field(read_screen=_read, sleep=sleep)
897
970
  pending: list = []
898
971
  if type_text is None:
899
972
  def type_text(text):
@@ -942,7 +1015,15 @@ def open_app(name: str, *, spotlight_open: bool = False,
942
1015
  # NORACU_PHONE_TIMEOUT_MS, or a slow start) — do not clear or type at all
943
1016
  tidy()
944
1017
  return "deadline"
945
- clear_text() # iOS kept the last query; new input would append
1018
+ # iOS kept the last query; new input would append. A clear that leaves text in the field (False)
1019
+ # stops here: the name typed after that text would not be found
1020
+ if clear_text() is False:
1021
+ tidy()
1022
+ return "not_cleared"
1023
+ if out_of_time():
1024
+ # reading the field after the clear can take the rest of the budget: nothing is typed then either
1025
+ tidy()
1026
+ return "deadline"
946
1027
  sleep(0.3)
947
1028
  try:
948
1029
  typed = type_text(name)
@@ -3,8 +3,7 @@
3
3
  Each gesture is followed by a screenshot hash comparison to confirm the
4
4
  screen actually changed. This closes the loop: an action that reports
5
5
  success but leaves the screen identical is a dropped event, and callers
6
- should retry or re-observe — the same observe-act-re-observe discipline
7
- that OpenAI's Computer Use enforces with its revision mechanism.
6
+ should retry or re-observe.
8
7
  """
9
8
 
10
9
  from __future__ import annotations
@@ -8,7 +8,7 @@ import Network
8
8
  // What this runner was built from: a hash of its own sources, kept up to date by scripts/gen-runner-build.mjs
9
9
  // (a test fails when it is not). It goes out on the ready line; the Mac side does not use a runner whose build
10
10
  // is not the one its own copy of these sources names.
11
- let noracuRunnerBuild = "b4383f0898e5"
11
+ let noracuRunnerBuild = "043fbc1f2a62"
12
12
 
13
13
  // MARK: - pure rules (no XCTest: test/ios-runner-rules.mjs compiles this block on its own and runs it)
14
14
 
@@ -331,7 +331,7 @@ enum RunnerCommands {
331
331
  }
332
332
  func walk(_ s: XCUIElementSnapshot) {
333
333
  if shown(s) && s.elementType == .icon { icons += 1 }
334
- // an alert only: a sheet's frame can cover the whole screen (pre-review P3)
334
+ // an alert only: a sheet's frame can cover the whole screen
335
335
  if shown(s) && s.elementType == .alert {
336
336
  var b: [CGRect] = []
337
337
  buttons(s, &b)
@@ -345,7 +345,7 @@ enum RunnerCommands {
345
345
 
346
346
  enum SBInput { case tap, press, drag, text }
347
347
 
348
- // review S4A-s8-g-1: a system alert (a permission prompt, say) sits over the app in front while the app still reads
348
+ // A system alert (a permission prompt, say) sits over the app in front while the app still reads
349
349
  // "in front", and the app's own snapshot does not show it. Input named for an app is not sent while one is up: a tap
350
350
  // at the app's point would press the alert's button, and text would go to the alert's field. SpringBoard that
351
351
  // cannot be read fails closed. Returns the refusal, or nil.
@@ -362,7 +362,7 @@ enum RunnerCommands {
362
362
  // tap whose point lies on a button of one of SpringBoard's alerts (a system prompt). A sheet does not count
363
363
  // (its frame can cover the screen), and nothing else is sent: no long press, no drag, no text and no key —
364
364
  // text goes wherever the keyboard focus is, which the public API does not show, and a second Return would
365
- // land on whatever the alert was covering (pre-review P3). Returns the refusal, or nil.
365
+ // land on whatever the alert was covering. Returns the refusal, or nil.
366
366
  @MainActor
367
367
  static func springboardRefusal(_ args: [String: Any], _ kind: SBInput, at point: CGPoint? = nil) -> [String: Any]? {
368
368
  guard let raw = args["springboard_only"] else { return nil }
@@ -452,7 +452,7 @@ enum RunnerCommands {
452
452
  case .tabBar: return "tabBar"
453
453
  case .table: return "table"
454
454
  case .textField: return "textField"
455
- case .secureTextField: return "secureTextField" // review S4A-s8-reviewer-1: it fell to "other"
455
+ case .secureTextField: return "secureTextField" // it used to fall to "other"
456
456
  case .textView: return "textView"
457
457
  case .toggle: return "toggle"
458
458
  case .toolbar: return "toolbar"
@@ -100,8 +100,7 @@ final class RunnerServer: @unchecked Sendable {
100
100
  return false
101
101
  }
102
102
  guard let rawId = obj["id"], !RunnerCommands.isBool(rawId), rawId is Int else {
103
- // a missing id, or one that is not a whole number, cannot be matched to its request: the command is not
104
- // run (pre-review P3 and P4)
103
+ // a missing id, or one that is not a whole number, cannot be matched to its request: the command is not run
105
104
  var no = RunnerCommands.fail(0, "invalid_args", "id must be a whole number", sent: RunnerCommands.inputOps.contains(obj["op"] as? String ?? "") ? false : nil)
106
105
  no["id"] = 0
107
106
  send(conn, no)
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "noracu",
3
- "version": "0.3.1",
3
+ "version": "0.3.3",
4
4
  "mcpName": "io.github.sgInnora/noracu",
5
- "description": "Local MCP server: macOS apps and a browser by element index, plus iPhone Mirroring (experimental).",
5
+ "description": "Local MCP server: operates Mac apps and a browser, sends no Mac input while you use the keyboard or mouse, and reports whether each input was delivered; iPhone layers are experimental and off by default.",
6
6
  "type": "module",
7
7
  "main": "src/server.mjs",
8
8
  "bin": {
@@ -10,10 +10,11 @@
10
10
  },
11
11
  "scripts": {
12
12
  "start": "node src/server.mjs",
13
- "test": "node test/engine-unit.mjs && node test/bg-inject-unit.mjs && node test/release-gate-unit.mjs && node test/gen-tools-unit.mjs && node test/cli-unit.mjs && node test/check-pack-unit.mjs && node test/docs-codes-unit.mjs && node test/ios-xcuitest-unit.mjs && node test/ios-session-unit.mjs && node test/ios-setup-unit.mjs && node test/ios-runner-rules.mjs && node test/ios-e2e.mjs && node test/e2e.mjs",
14
- "test:ci": "node test/engine-unit.mjs && node test/bg-inject-unit.mjs && node test/release-gate-unit.mjs && node test/gen-tools-unit.mjs && node test/cli-unit.mjs && node test/check-pack-unit.mjs && node test/docs-codes-unit.mjs && node test/ios-xcuitest-unit.mjs && node test/ios-session-unit.mjs && node test/ios-setup-unit.mjs && node test/ios-runner-rules.mjs && node test/ios-e2e.mjs && NORACU_CI=1 node test/e2e.mjs",
13
+ "build:mcpb": "node scripts/build-mcpb.mjs",
14
+ "test": "node test/engine-unit.mjs && node test/bg-inject-unit.mjs && node test/release-gate-unit.mjs && node test/gen-tools-unit.mjs && node test/cli-unit.mjs && node test/cli-no-cliclick.mjs && node test/check-pack-unit.mjs && node test/mcpb-unit.mjs && node test/docs-codes-unit.mjs && node test/error-texts.mjs && node test/error-literals-unit.mjs && node test/ios-xcuitest-unit.mjs && node test/ios-session-unit.mjs && node test/ios-setup-unit.mjs && node test/ios-runner-rules.mjs && node test/ios-e2e.mjs && node test/e2e.mjs && node test/browser-scroll-slow.mjs",
15
+ "test:ci": "node test/engine-unit.mjs && node test/bg-inject-unit.mjs && node test/release-gate-unit.mjs && node test/gen-tools-unit.mjs && node test/cli-unit.mjs && node test/cli-no-cliclick.mjs && node test/check-pack-unit.mjs && node test/mcpb-unit.mjs && node test/docs-codes-unit.mjs && node test/error-texts.mjs && node test/error-literals-unit.mjs && node test/ios-xcuitest-unit.mjs && node test/ios-session-unit.mjs && node test/ios-setup-unit.mjs && node test/ios-runner-rules.mjs && node test/ios-e2e.mjs && NORACU_CI=1 node test/e2e.mjs && node test/browser-scroll-slow.mjs",
15
16
  "test:imctl": "cd imctl && ${NORACU_PYTHON:-python3} tests/test_smoke.py",
16
- "check": "node --check src/server.mjs && node --check src/mac-ax.js && node --check src/approval.js && node --check src/bg-inject.js && node --check src/ios-xcuitest.js && node --check src/ios-session.js && node --check src/ios-setup.js && node --check src/doctor.js && node --check scripts/gen-tools.mjs && node --check scripts/release-gate.mjs && node --check scripts/check-pack.mjs && node --check scripts/pack-rules.mjs && python3 -c \"import ast,sys; [ast.parse(open(f).read(), f) for f in sys.argv[1:]]\" imctl/src/imctl/*.py",
17
+ "check": "node --check src/server.mjs && node --check src/mcpb-entry.js && node --check src/mac-ax.js && node --check src/approval.js && node --check src/bg-inject.js && node --check src/ios-xcuitest.js && node --check src/ios-session.js && node --check src/ios-setup.js && node --check src/doctor.js && node --check scripts/gen-tools.mjs && node --check scripts/release-gate.mjs && node --check scripts/check-pack.mjs && node --check scripts/pack-rules.mjs && node --check scripts/check-public.mjs && node --check scripts/mcpb-manifest.mjs && node --check scripts/build-mcpb.mjs && node scripts/check-public.mjs && node --check scripts/check-copy.mjs && node scripts/check-copy.mjs && python3 -c \"import ast,sys; [ast.parse(open(f).read(), f) for f in sys.argv[1:]]\" imctl/src/imctl/*.py",
17
18
  "prepublishOnly": "npm run check && node scripts/release-gate.mjs && node scripts/check-pack.mjs && node scripts/gen-tools.mjs && git diff --exit-code docs/tools.md"
18
19
  },
19
20
  "engines": {
@@ -24,18 +25,21 @@
24
25
  "mcp-server",
25
26
  "model-context-protocol",
26
27
  "computer-use",
27
- "playwright",
28
+ "mac",
28
29
  "macos",
29
30
  "macos-automation",
31
+ "accessibility",
32
+ "desktop-automation",
33
+ "ui-automation",
30
34
  "browser-automation",
35
+ "playwright",
31
36
  "claude",
32
37
  "claude-desktop",
33
38
  "claude-code",
34
39
  "cursor",
40
+ "ai-agent",
35
41
  "iphone",
36
42
  "iphone-mirroring",
37
- "accessibility",
38
- "desktop-automation",
39
43
  "xcuitest"
40
44
  ],
41
45
  "license": "MIT",
package/src/approval.js CHANGED
@@ -42,20 +42,31 @@ const TERMINALS = [
42
42
  { bundle: "org.tabby", path: /\/Tabby\.app\//i },
43
43
  { bundle: "com.raphaelamorim.rio", path: /\/Rio\.app\/|\/rio$/i },
44
44
  { bundle: "dev.commandline.waveterm", path: /\/Wave\.app\//i },
45
+ // Orca, an agent IDE whose terminals run a shell (appId and productName from its electron-builder config, and its
46
+ // Homebrew cask, 2026-11-19). On this list rather than with the IDEs so that a client running in one of its
47
+ // terminals is recognised as hosted by it too: its helper processes live inside Orca.app
48
+ { bundle: "com.stablyai.orca", path: /\/Orca\.app\//i },
45
49
  ];
46
50
 
47
51
  // --- host terminal (resolved once): the first ancestor that is a terminal app; tmux / screen are walked
48
52
  // through. Returns { bundle } for a listed terminal, { name } for another app bundle named like a terminal,
49
53
  // or null (chain broken, no terminal found).
54
+ // What one ancestor's executable path says: { bundle } for a listed terminal (a helper inside its .app counts),
55
+ // { name } for another app bundle named like a terminal, null for anything else. Exported for the tests.
56
+ export function terminalFromPath(comm) {
57
+ const t = TERMINALS.find((x) => x.path.test(comm));
58
+ if (t) return { bundle: t.bundle };
59
+ const app = /\/([^/]+)\.app\/Contents\/MacOS\/[^/]+$/.exec(comm);
60
+ if (app && /term|shell|console/i.test(app[1])) return { name: app[1] };
61
+ return null;
62
+ }
50
63
  function hostTerminal() {
51
64
  try {
52
65
  let pid = process.ppid;
53
66
  for (let i = 0; i < 12 && pid > 1; i++) {
54
67
  const comm = execFileSync("/bin/ps", ["-o", "comm=", "-p", String(pid)], { encoding: "utf8", timeout: 2000 }).trim();
55
- const t = TERMINALS.find((x) => x.path.test(comm));
56
- if (t) return { bundle: t.bundle };
57
- const app = /\/([^/]+)\.app\/Contents\/MacOS\/[^/]+$/.exec(comm);
58
- if (app && /term|shell|console/i.test(app[1])) return { name: app[1] };
68
+ const t = terminalFromPath(comm);
69
+ if (t) return t;
59
70
  // anything else — a shell, node, npm, tmux, screen — is walked through to its parent
60
71
  const ppidLine = execFileSync("/bin/ps", ["-o", "ppid=", "-p", String(pid)], { encoding: "utf8", timeout: 2000 }).trim();
61
72
  pid = Number(ppidLine);
@@ -67,7 +78,7 @@ function hostTerminal() {
67
78
  const HOST_TERMINAL = hostTerminal();
68
79
 
69
80
  // the same apps by name too, for an app whose bundle id cannot be read (Warp Preview was missed)
70
- const TERMINAL_NAMES = ["Terminal", "iTerm2", "iTerm", "WezTerm", "Ghostty", "Warp*", "Alacritty", "kitty", "Hyper", "Tabby", "Rio", "Wave"];
81
+ const TERMINAL_NAMES = ["Terminal", "iTerm2", "iTerm", "WezTerm", "Ghostty", "Warp*", "Alacritty", "kitty", "Hyper", "Tabby", "Rio", "Wave", "Orca"];
71
82
  // IDEs with a built-in terminal (2026-11-12): keys typed into one can reach its shell, so
72
83
  // they get no input by default either. Bundle ids (VS Code and Cursor read from installed apps), and names,
73
84
  // which also match when the bundle id is read but differs (a fork, an edition)
@@ -107,13 +118,14 @@ export function gateActive() {
107
118
  export function stopFileBlocked() {
108
119
  const p = process.env.NORACU_STOP_FILE;
109
120
  if (p === undefined) return null;
110
- if (!p.trim()) return "stop_check_error: NORACU_STOP_FILE is set but blank — remove it or give a path; nothing was sent (fail closed; delivery=not_delivered, retry=safe)";
121
+ if (!p.trim()) return "stop_check_error: NORACU_STOP_FILE is set but blank — stop and tell the person to give it a path or unset it; do not retry or work around it (delivery=not_delivered, retry=safe)";
111
122
  try {
112
123
  statSync(p);
113
- return `user_stopped: ${p} exists — the person at the Mac stopped noracu's input; nothing was sent (delivery=not_delivered, retry=safe); remove the file to resume`;
124
+ // the file is the person's brake: the agent stops, says so, and leaves the file alone
125
+ return `user_stopped: the person at the Mac stopped noracu's input (${p.slice(0, 80)} exists) — stop and tell the person; do not remove that file, retry or work around it (delivery=not_delivered, retry=safe)`;
114
126
  } catch (e) {
115
127
  if (e && e.code === "ENOENT") return null;
116
- return `stop_check_error: could not check ${p} (${e && e.code ? e.code : "unknown"}) — nothing was sent (fail closed; delivery=not_delivered, retry=safe)`;
128
+ return `stop_check_error: could not check ${p.slice(0, 80)} (${e && e.code ? e.code : "unknown"}) — stop and tell the person; do not retry or work around it (delivery=not_delivered, retry=safe)`;
117
129
  }
118
130
  }
119
131
 
@@ -128,7 +140,11 @@ function matches(pattern, bundleId, appName) {
128
140
 
129
141
  // a rule written as a bundle id ("com.apple.Terminal", "com.example.*"); anything else names apps by their name
130
142
  const byBundle = (p) => /^[\w*?-]+(\.[\w*?-]+)+$/.test(String(p).trim());
131
- const unnamed = (what) => ({ error: `input_denied: the name of the app that would receive the input could not be read, so ${what} cannot rule it out — nothing was sent (fail closed; delivery=not_delivered, retry=safe)` });
143
+ // A refusal only the person can lift: what is wrong, then what the agent does.
144
+ const PERSON = "stop and tell the person; do not retry or work around it (delivery=not_delivered, retry=safe)";
145
+ const unnamed = (what) => ({ error: `input_denied: the name of the app that would receive the input could not be read, so ${what} cannot check it — ${PERSON}` });
146
+ // a broken approval file: its path (cut to 80 characters) and what is wrong with it
147
+ const broken = (code, file, what) => ({ error: `${code}: ${String(file).slice(0, 80)} ${what} — stop and tell the person to fix NORACU_APPROVAL_FILE; do not retry or work around it (delivery=not_delivered, retry=safe)` });
132
148
 
133
149
  // --- approval file (opt-in). Returns { verdict: "allow"|"ask"|"deny", reason } or { error } (fail closed). ---
134
150
  // needName: the app has a name to read (a Mac app). Without one, a rule that names apps cannot rule it out, so the
@@ -139,7 +155,7 @@ export function evaluateApproval({ bundleId, appName, needName = false } = {}) {
139
155
  // both; this keeps the module safe on its own)
140
156
  const bid = String(bundleId ?? "").trim(), name = String(appName ?? "").trim();
141
157
  if (!bid && (!name || gateActive())) {
142
- return { error: `input_denied: the app that would receive the input ${name ? `("${name}") has no readable bundle id, so the deny list / approval file cannot rule it out` : "could not be identified"} — nothing was sent (fail closed; delivery=not_delivered, retry=safe)` };
158
+ return { error: `input_denied: the app that would receive the input ${name ? `("${name}") has no readable bundle id, so app rules cannot check it` : "could not be identified"} — ${PERSON}` };
143
159
  }
144
160
  const deny = denyList();
145
161
  // how many entries at the head of the list the user wrote (NORACU_DENY_APPS): those always win. The rest is the
@@ -148,18 +164,18 @@ export function evaluateApproval({ bundleId, appName, needName = false } = {}) {
148
164
  let byDefault = null;
149
165
  // the trimmed bundle id and name are what every rule is matched against, as they are what was checked above
150
166
  // (" com.apple.Terminal" was checked as known and then missed the deny list)
167
+ // the reason is read after the app's name ("Terminal" is …): which list named it, and for the default list what
168
+ // the person can do about it
151
169
  for (const [i, d] of deny.list.entries()) if (matches(d, bid, name)) {
152
- // with a list of the user's own, say which of the two lists named the app
153
- const src = deny.own === undefined ? deny.source : i < deny.own ? "NORACU_DENY_APPS" : "the default deny list (terminal apps and IDEs with a terminal)";
154
- if (i < userCount) return { verdict: "deny", reason: `denied by ${src} ("${d}")` };
155
- byDefault = { verdict: "deny", reason: `denied by ${src} ("${d}") — the person at the Mac can let this one app through by naming it exactly (no * or ?) under "allow" in an approval file (NORACU_APPROVAL_FILE)` };
170
+ if (i < userCount) return { verdict: "deny", reason: `on NORACU_DENY_APPS ("${d}")` };
171
+ byDefault = { verdict: "deny", reason: `on the default deny list of terminals and IDEs ("${d}"); the person can allow it by naming it exactly in an approval file` };
156
172
  break;
157
173
  }
158
174
  // the default list names some apps by name (editions and forks whose bundle id differs)
159
175
  if (needName && !name && !byDefault && deny.list.some((d) => !byBundle(d))) return unnamed("the deny list's entries that name apps");
160
176
  const file = process.env.NORACU_APPROVAL_FILE;
161
177
  if (file === undefined) return byDefault || { verdict: "allow" };
162
- if (!file.trim()) return { error: "approval_file_error: NORACU_APPROVAL_FILE is set but blank — remove it or give a path; nothing was sent (fail closed; delivery=not_delivered, retry=safe)" };
178
+ if (!file.trim()) return { error: `approval_file_error: NORACU_APPROVAL_FILE is set but blank — stop and tell the person to give it a path or unset it; do not retry or work around it (delivery=not_delivered, retry=safe)` };
163
179
  let conf;
164
180
  let fd = null;
165
181
  try {
@@ -168,30 +184,30 @@ export function evaluateApproval({ bundleId, appName, needName = false } = {}) {
168
184
  // to it; the open descriptor is then refused as not a regular file
169
185
  fd = openSync(file, fsc.O_RDONLY | fsc.O_NOFOLLOW | fsc.O_NONBLOCK);
170
186
  const st = fstatSync(fd);
171
- if (!st.isFile()) return { error: `approval_file_error: ${file} is not a regular file — nothing was sent (fail closed; delivery=not_delivered, retry=safe)` };
172
- if (st.mode & 0o077) return { error: `approval_file_insecure: ${file} must be mode 0600 (is 0${(st.mode & 0o777).toString(8)}) — nothing was sent (fail closed; delivery=not_delivered, retry=safe)` };
173
- if (st.uid !== process.getuid?.()) return { error: `approval_file_owner: ${file} is not owned by this user — nothing was sent (fail closed; delivery=not_delivered, retry=safe)` };
187
+ if (!st.isFile()) return broken("approval_file_error", file, "is not a regular file");
188
+ if (st.mode & 0o077) return broken("approval_file_insecure", file, `must be mode 0600 (it is 0${(st.mode & 0o777).toString(8)})`);
189
+ if (st.uid !== process.getuid?.()) return broken("approval_file_owner", file, "is not owned by this user");
174
190
  // a list of apps is small: a file over 64 KB is not read at all (it is read again before every input)
175
- if (st.size > 65536) return { error: `approval_file_error: ${file} is larger than 64 KB — nothing was sent (fail closed; delivery=not_delivered, retry=safe)` };
191
+ if (st.size > 65536) return broken("approval_file_error", file, "is larger than 64 KB");
176
192
  const text = readFileSync(fd, "utf8");
177
193
  // JSON.parse's message quotes a piece of the file, and this answer goes to the agent: it is not passed on
178
194
  try { conf = JSON.parse(text); } catch {
179
- return { error: `approval_file_error: ${file} is not valid JSON — NORACU_APPROVAL_FILE is set, so nothing was sent (fail closed; delivery=not_delivered, retry=safe)` };
195
+ return broken("approval_file_error", file, "is not valid JSON");
180
196
  }
181
197
  } catch (e) {
182
198
  const why = e && e.code === "ENOENT" ? "does not exist" : e && e.code === "ELOOP" ? "is a symlink" : `is unreadable or not JSON (${e && e.code ? e.code : String(e).slice(0, 80)})`;
183
- return { error: `approval_file_error: ${file} ${why} — NORACU_APPROVAL_FILE is set, so nothing was sent (fail closed; delivery=not_delivered, retry=safe)` };
199
+ return broken("approval_file_error", file, why);
184
200
  } finally {
185
201
  if (fd !== null) try { closeSync(fd); } catch { /* already closed */ }
186
202
  }
187
- if (!conf || typeof conf !== "object" || Array.isArray(conf)) return { error: `approval_file_error: ${file} must hold a JSON object — nothing was sent (fail closed; delivery=not_delivered, retry=safe)` };
203
+ if (!conf || typeof conf !== "object" || Array.isArray(conf)) return broken("approval_file_error", file, "must hold a JSON object");
188
204
  const unknown = Object.keys(conf).filter((k) => !["allow", "ask", "deny"].includes(k));
189
- if (unknown.length) return { error: `approval_file_error: ${file} has unknown key(s) ${unknown.slice(0, 3).map((k) => JSON.stringify(k)).join(", ")} — only "allow", "ask" and "deny"; nothing was sent (fail closed; delivery=not_delivered, retry=safe)` };
190
- for (const key of ["allow", "ask", "deny"]) if (conf[key] !== undefined && !Array.isArray(conf[key])) return { error: `approval_file_error: "${key}" must be an array — nothing was sent (fail closed; delivery=not_delivered, retry=safe)` };
205
+ if (unknown.length) return broken("approval_file_error", file, `has unknown key(s) ${unknown.slice(0, 3).map((k) => JSON.stringify(k).slice(0, 30)).join(", ")} (only "allow", "ask" and "deny")`);
206
+ for (const key of ["allow", "ask", "deny"]) if (conf[key] !== undefined && !Array.isArray(conf[key])) return broken("approval_file_error", file, `has "${key}" that is not an array`);
191
207
  // an empty or non-string pattern is a broken file, not a pattern
192
- for (const key of ["allow", "ask", "deny"]) for (const p of conf[key] || []) if (typeof p !== "string" || !p.trim() || p.length > 200) return { error: `approval_file_error: "${key}" holds an empty or non-string pattern (${JSON.stringify(p)?.slice(0, 40)}) — nothing was sent (fail closed; delivery=not_delivered, retry=safe)` };
208
+ for (const key of ["allow", "ask", "deny"]) for (const p of conf[key] || []) if (typeof p !== "string" || !p.trim() || p.length > 200) return broken("approval_file_error", file, `has an empty or non-string pattern in "${key}" (${JSON.stringify(p)?.slice(0, 40)})`);
193
209
  if (needName && !name && [...(conf.deny || []), ...(conf.ask || [])].some((p) => !byBundle(p))) return unnamed(`the entries of ${file} that name apps`);
194
- for (const d of conf.deny || []) if (matches(d, bid, name)) return { verdict: "deny", reason: `denied by approval file ("${d}")` };
210
+ for (const d of conf.deny || []) if (matches(d, bid, name)) return { verdict: "deny", reason: `denied by the approval file ("${d}")` };
195
211
  // on the default deny list: only an "allow" entry that names this app — its bundle id or its name, without a
196
212
  // wildcard — lets it through; "*" or "com.example.*" in "allow" does not open a terminal
197
213
  if (byDefault) {
@@ -199,9 +215,9 @@ export function evaluateApproval({ bundleId, appName, needName = false } = {}) {
199
215
  return byDefault;
200
216
  }
201
217
  for (const a of conf.ask || []) if (matches(a, bid, name)) {
202
- return { verdict: "ask", reason: `approval_required: "${bundleId || appName}" is listed under "ask" in ${file} — the person at the Mac must move it to "allow" (noracu never edits this file); nothing was sent (delivery=not_delivered, retry=safe)` };
218
+ return { verdict: "ask", reason: `approval_required: "${bundleId || appName}" is listed under "ask" in the approval file — stop and tell the person, who decides by moving it to "allow"; do not edit the file, retry or work around it (delivery=not_delivered, retry=safe)` };
203
219
  }
204
220
  for (const a of conf.allow || []) if (matches(a, bid, name)) return { verdict: "allow", reason: `allowed by approval file ("${a}")` };
205
221
  // nothing matched: ask (an approval file that lists apps but not this one means "ask")
206
- return { verdict: "ask", reason: `approval_required: ${file} lists apps but not "${bundleId || appName}" — add it to "allow" or "deny"; nothing was sent (delivery=not_delivered, retry=safe)` };
222
+ return { verdict: "ask", reason: `approval_required: "${bundleId || appName}" is not listed in the approval file — stop and tell the person, who decides by adding it to "allow" or "deny"; do not edit the file, retry or work around it (delivery=not_delivered, retry=safe)` };
207
223
  }