@staix/agent-hub 0.51.0 → 0.52.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +35 -0
- package/README.md +1 -1
- package/docs/adding-an-ai-tool.md +24 -2
- package/docs/agent-notes/adapters.md +1 -0
- package/docs/agent-notes/budget.md +8 -2
- package/docs/agent-notes/daemon.md +13 -8
- package/docs/agent-notes/security-review.md +6 -5
- package/docs/agent-notes/tasks.md +5 -2
- package/docs/agent-notes/tests.md +4 -3
- package/docs/cooperbench.md +1 -1
- package/docs/design/adapters.md +4 -0
- package/docs/design/cli-output-inventory.md +162 -152
- package/docs/design/cli-output.md +4 -3
- package/docs/design/guidance-probes.md +1 -0
- package/docs/design/roadmap.md +2 -0
- package/docs/design/task-board.md +1 -0
- package/docs/dogfood.md +14 -0
- package/docs/events.md +4 -2
- package/docs/memory.md +5 -3
- package/docs/operations.md +210 -16
- package/docs/quickstart.md +12 -2
- package/docs/roles.md +1 -1
- package/docs/sdlc.md +26 -3
- package/docs/security.md +11 -5
- package/docs/specs/2026-09-19-agent-hub-design.md +43 -0
- package/docs/specs/2026-09-19-multi-project-design.md +4 -0
- package/docs/specs/2026-09-20-upgrade-recovery-design.md +17 -0
- package/docs/specs/mcp-endpoint.md +63 -0
- package/docs/verification/2026-11-30-capability-listing-shape-1808.md +45 -0
- package/docs/verification/2026-11-30-upgrade-keep-1807.md +174 -0
- package/docs/verification/2026-12-01-1811-confirmation-receipt.md +19 -0
- package/docs/verification/2026-12-01-1811-orca-agent-list.md +20 -0
- package/docs/verification/2026-12-01-1811-orca-pane-key.md +21 -0
- package/docs/verification/2026-12-02-1819-claude-process-after-renewal.md +54 -0
- package/docs/verification/2026-12-02-agy-1.5.21.md +74 -0
- package/docs/verification/2026-12-02-claude-implementer-2.1.334.md +44 -0
- package/docs/verification/2026-12-02-cli-import-graph.md +33 -0
- package/docs/verification/2026-12-03-0.52.0.md +150 -0
- package/docs/verification/2026-12-03-codex-0173-reviewer-isolation.md +53 -0
- package/docs/verification/2026-12-03-codex-0173-reviewer-tool-call.md +34 -0
- package/docs/verification/2026-12-03-jcode-1.3.0.md +25 -0
- package/docs/verification/agy/README.md +17 -0
- package/docs/verification/agy/cli-surface.ts +68 -0
- package/docs/verification/agy/interactive-bridge.ts +92 -0
- package/docs/verification/agy/interactive-session.ts +131 -0
- package/docs/verification/agy/launcher-nonce.ts +215 -0
- package/docs/verification/agy/native-hooks.ts +210 -0
- package/docs/verification/agy/originals/agent-hub-681/cli-surface.ts +87 -0
- package/docs/verification/agy/originals/agent-hub-681/native-hooks-adapted.ts +91 -0
- package/docs/verification/agy/originals/agent-hub-681/tui-actual.ts +200 -0
- package/docs/verification/agy/originals/agent-hub-684/probe.ts +107 -0
- package/docs/verification/agy/originals.json +25 -0
- package/docs/verification/agy/permission-new-functions.ts +128 -0
- package/docs/verification/agy/run-probe.py +108 -0
- package/docs/verification/agy/runtime.ts +171 -0
- package/docs/verification/agy/tmux-helper-control.ts +6 -0
- package/docs/verification/agy/tmux-session.ts +235 -0
- package/docs/verified.json +82 -41
- package/package.json +3 -3
- package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
- package/plugins/agent-hub/compat.json +157 -0
- package/plugins/agent-hub/kimi-hook.js +621 -865
- package/plugins/agent-hub/server.js +17423 -32962
- package/src/adapters/agy/definition.ts +7 -24
- package/src/adapters/channel-peer.ts +3 -1
- package/src/adapters/claude-channel.ts +38 -257
- package/src/adapters/claude-implementer.ts +3 -1
- package/src/adapters/codex-appserver.ts +77 -15
- package/src/adapters/compat.ts +74 -11
- package/src/adapters/configured-acp.ts +23 -163
- package/src/adapters/configured-adapter-policy.ts +160 -0
- package/src/adapters/configured-pull-entry.ts +53 -0
- package/src/adapters/configured-pull.ts +38 -0
- package/src/adapters/conformance/fakes/app-server.ts +9 -2
- package/src/adapters/declaration-catalog.ts +25 -0
- package/src/adapters/declaration-data.ts +342 -0
- package/src/adapters/declaration-resolution.ts +53 -0
- package/src/adapters/definitions/builtin-metadata.ts +61 -83
- package/src/adapters/definitions/jcode-launch.ts +13 -0
- package/src/adapters/definitions/native-adapter-policy.ts +390 -0
- package/src/adapters/definitions/native-cli-claude-launch.ts +3 -2
- package/src/adapters/definitions/native-cli-codex-launch.ts +2 -1
- package/src/adapters/definitions/native-cli-entry-jcode.ts +4 -2
- package/src/adapters/definitions/native-cli-entry-types.ts +9 -2
- package/src/adapters/definitions/native-cli-launch-common.ts +2 -2
- package/src/adapters/definitions/native-cli-retained.ts +1 -1
- package/src/adapters/definitions/native-configuration.ts +18 -0
- package/src/adapters/definitions/native-help.ts +24 -0
- package/src/adapters/definitions/native-launch-declarations.ts +34 -0
- package/src/adapters/definitions/native-launch-policy.ts +4 -0
- package/src/adapters/definitions/native-launch-settings.ts +72 -0
- package/src/adapters/definitions/native-light-cli.ts +18 -0
- package/src/adapters/definitions/native-light-preview.ts +10 -0
- package/src/adapters/definitions/native-wrapper-launch.ts +10 -0
- package/src/adapters/definitions/qwen.ts +6 -29
- package/src/adapters/definitions/reviewer-variants.ts +7 -8
- package/src/adapters/external-declarations.ts +31 -0
- package/src/adapters/external-modules.ts +4 -29
- package/src/adapters/jcode.ts +3 -12
- package/src/adapters/native-capabilities.ts +18 -8
- package/src/adapters/native-proof-ports.ts +1 -1
- package/src/adapters/presets.ts +136 -0
- package/src/adapters/qwen-dual.ts +2 -2
- package/src/adapters/registry-types.ts +3 -0
- package/src/adapters/registry.ts +20 -81
- package/src/adapters/reviewer-print.ts +26 -9
- package/src/adapters/role-eligibility.ts +2 -1
- package/src/cli/accounts-import.ts +72 -0
- package/src/cli/agents-latest-table.ts +88 -0
- package/src/cli/agents-latest.ts +22 -0
- package/src/cli/agents-output.ts +10 -0
- package/src/cli/agents-presets.ts +100 -0
- package/src/cli/agents.ts +1 -1
- package/src/cli/attention.ts +3 -2
- package/src/cli/autonomy-homes.ts +7 -2
- package/src/cli/budget-renew-guidance.ts +129 -0
- package/src/cli/claude-homes.ts +9 -5
- package/src/cli/command-context.ts +3 -0
- package/src/cli/command-table.ts +123 -0
- package/src/cli/commands/accounts.ts +8 -0
- package/src/cli/commands/agents.ts +18 -0
- package/src/cli/commands/answer.ts +28 -0
- package/src/cli/commands/ask.ts +17 -0
- package/src/cli/commands/autonomy.ts +83 -0
- package/src/cli/commands/backlog.ts +46 -0
- package/src/cli/commands/bench.ts +60 -0
- package/src/cli/commands/board.ts +48 -0
- package/src/cli/commands/broker.ts +9 -0
- package/src/cli/commands/budget.ts +96 -0
- package/src/cli/commands/capabilities.ts +12 -0
- package/src/cli/commands/check-path.ts +55 -0
- package/src/cli/commands/completion.ts +8 -0
- package/src/cli/commands/console.ts +12 -0
- package/src/cli/commands/daemon.ts +8 -0
- package/src/cli/commands/deliverables.ts +25 -0
- package/src/cli/commands/doctor.ts +249 -0
- package/src/cli/commands/down.ts +3 -0
- package/src/cli/commands/export.ts +15 -0
- package/src/cli/commands/facts.ts +15 -0
- package/src/cli/commands/goal.ts +22 -0
- package/src/cli/commands/guidance.ts +102 -0
- package/src/cli/commands/help.ts +17 -0
- package/src/cli/commands/host.ts +45 -0
- package/src/cli/commands/init.ts +121 -0
- package/src/cli/commands/instructed.ts +19 -0
- package/src/cli/commands/instruction-hook.ts +15 -0
- package/src/cli/commands/intake.ts +24 -0
- package/src/cli/commands/kill.ts +15 -0
- package/src/cli/commands/learn.ts +23 -0
- package/src/cli/commands/lineage.ts +30 -0
- package/src/cli/commands/logs.ts +21 -0
- package/src/cli/commands/manager.ts +15 -0
- package/src/cli/commands/memory.ts +21 -0
- package/src/cli/commands/model.ts +25 -0
- package/src/cli/commands/models.ts +40 -0
- package/src/cli/commands/native.ts +39 -0
- package/src/cli/commands/pause.ts +5 -0
- package/src/cli/commands/peer.ts +32 -0
- package/src/cli/commands/permission.ts +26 -0
- package/src/cli/commands/permit.ts +12 -0
- package/src/cli/commands/pet.ts +24 -0
- package/src/cli/commands/projects.ts +49 -0
- package/src/cli/commands/queue.ts +70 -0
- package/src/cli/commands/recovery-run.ts +13 -0
- package/src/cli/commands/recovery.ts +130 -0
- package/src/cli/commands/release.ts +23 -0
- package/src/cli/commands/releases.ts +9 -0
- package/src/cli/commands/remember.ts +6 -0
- package/src/cli/commands/report.ts +27 -0
- package/src/cli/commands/research.ts +53 -0
- package/src/cli/commands/reset.ts +89 -0
- package/src/cli/commands/restart.ts +5 -0
- package/src/cli/commands/results.ts +31 -0
- package/src/cli/commands/resume.ts +5 -0
- package/src/cli/commands/review.ts +24 -0
- package/src/cli/commands/roadmap.ts +21 -0
- package/src/cli/commands/role.ts +34 -0
- package/src/cli/commands/roles.ts +30 -0
- package/src/cli/commands/room.ts +14 -0
- package/src/cli/commands/roster.ts +48 -0
- package/src/cli/commands/route.ts +9 -0
- package/src/cli/commands/say.ts +21 -0
- package/src/cli/commands/schedule.ts +17 -0
- package/src/cli/commands/sdlc.ts +321 -0
- package/src/cli/commands/settings.ts +148 -0
- package/src/cli/commands/setup.ts +89 -0
- package/src/cli/commands/shared-refusals.ts +25 -0
- package/src/cli/commands/smoke.ts +44 -0
- package/src/cli/commands/source.ts +64 -0
- package/src/cli/commands/specs.ts +13 -0
- package/src/cli/commands/status.ts +28 -0
- package/src/cli/commands/stop.ts +17 -0
- package/src/cli/commands/structure.ts +60 -0
- package/src/cli/commands/study.ts +39 -0
- package/src/cli/commands/tail.ts +19 -0
- package/src/cli/commands/task.ts +114 -0
- package/src/cli/commands/title.ts +17 -0
- package/src/cli/commands/turns.ts +10 -0
- package/src/cli/commands/ui.ts +47 -0
- package/src/cli/commands/undo.ts +77 -0
- package/src/cli/commands/up.ts +39 -0
- package/src/cli/commands/upgrade.ts +5 -0
- package/src/cli/commands/usage.ts +33 -0
- package/src/cli/commands/version.ts +5 -0
- package/src/cli/commands/watch.ts +30 -0
- package/src/cli/commands/worktrees.ts +31 -0
- package/src/cli/console-state.ts +5 -138
- package/src/cli/console-versions.ts +1 -1
- package/src/cli/help.ts +37 -15
- package/src/cli/identity.ts +23 -4
- package/src/cli/launch-check.ts +1 -2
- package/src/cli/launch.ts +13 -82
- package/src/cli/light-dispatch.ts +29 -0
- package/src/cli/main.js +8 -1
- package/src/cli/main.ts +233 -2816
- package/src/cli/orca-probe.ts +119 -0
- package/src/cli/output.ts +31 -2
- package/src/cli/preview.ts +10 -5
- package/src/cli/recovery-version-preflight.ts +28 -9
- package/src/cli/replace-process.ts +22 -0
- package/src/cli/report-layout.ts +142 -0
- package/src/cli/roadmap-usage.ts +16 -0
- package/src/cli/roadmap.ts +3 -16
- package/src/cli/sdlc-doctor.ts +27 -0
- package/src/cli/sdlc-output.ts +55 -1
- package/src/cli/setup-homes.ts +1 -1
- package/src/cli/start-agents-run.ts +1 -1
- package/src/cli/statusline-tee.ts +25 -4
- package/src/cli/terminal-recovery.ts +53 -10
- package/src/cli/upgrade-interactive.ts +1 -0
- package/src/cli/upgrade-runtime.ts +11 -0
- package/src/cli/upgrade.ts +4 -15
- package/src/hub/accounts.ts +148 -0
- package/src/hub/addons.ts +20 -0
- package/src/hub/agent-drift.ts +2 -1
- package/src/hub/budget-projection.ts +39 -7
- package/src/hub/budget.ts +231 -16
- package/src/hub/channel-project.ts +3 -3
- package/src/hub/conductor-peer.ts +24 -0
- package/src/hub/conductor.ts +2 -21
- package/src/hub/config-apply.ts +24 -13
- package/src/hub/config-edit.ts +1 -1
- package/src/hub/config-tier.ts +2 -0
- package/src/hub/config.ts +31 -14
- package/src/hub/control-client.ts +48 -0
- package/src/hub/daemon.ts +421 -61
- package/src/hub/events.ts +3 -0
- package/src/hub/home-tag.ts +12 -0
- package/src/hub/host.ts +217 -0
- package/src/hub/hub-tools.ts +2 -1
- package/src/hub/instance-budget.ts +2 -2
- package/src/hub/instance-config.ts +15 -126
- package/src/hub/instances.ts +22 -6
- package/src/hub/instruction-receipt.ts +2 -2
- package/src/hub/kimi-usage.ts +38 -11
- package/src/hub/lifecycle.ts +86 -4
- package/src/hub/mcp-bridge-core.ts +98 -0
- package/src/hub/mcp-channel-push.ts +20 -0
- package/src/hub/mcp-endpoint-serve.ts +178 -0
- package/src/hub/mcp-endpoint.ts +226 -0
- package/src/hub/mcp-tool-call.ts +181 -0
- package/src/hub/operational-settings.ts +2 -0
- package/src/hub/orca-env.ts +6 -0
- package/src/hub/orca-state.ts +84 -0
- package/src/hub/peers.ts +5 -1
- package/src/hub/permission-mode.ts +2 -1
- package/src/hub/project.ts +20 -0
- package/src/hub/protocol-window.ts +58 -0
- package/src/hub/quota-origin.ts +20 -0
- package/src/hub/registry.ts +36 -2
- package/src/hub/report.ts +1 -1
- package/src/hub/research.ts +1 -1
- package/src/hub/review-brief.ts +47 -2
- package/src/hub/roster.ts +6 -3
- package/src/hub/routing.ts +9 -2
- package/src/hub/sdlc-check.ts +205 -0
- package/src/hub/sdlc-sync.ts +146 -0
- package/src/hub/sdlc.ts +33 -4
- package/src/hub/settings.ts +7 -4
- package/src/hub/start-agents.ts +1 -1
- package/src/hub/start-mode.ts +11 -4
- package/src/hub/structure-budget.ts +131 -0
- package/src/hub/structure-scan.ts +149 -0
- package/src/hub/tasks-experiment.ts +455 -0
- package/src/hub/tasks-guidance.ts +606 -0
- package/src/hub/tasks-roadmap-plan.ts +419 -0
- package/src/hub/tasks-roadmap.ts +491 -0
- package/src/hub/tasks-study.ts +661 -0
- package/src/hub/tasks-survey.ts +192 -0
- package/src/hub/tasks.ts +319 -2548
- package/src/hub/terminal-open.ts +5 -3
- package/src/hub/tooling.ts +3 -19
- package/src/hub/usage-rollup.ts +9 -3
- package/src/local/tools.ts +5 -0
- package/src/ui/index.html +1 -1
- package/src/ui/needs.ts +17 -5
- package/src/ui/peer-palette.ts +2 -4
- package/templates/presets/agents.json +60 -0
- package/templates/presets/confirmation-matrix.json +8 -8
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""task801 controller, kept in the repository. Requires explicit owned invocation with a scratch copy of the binary; never installs or admits a real machine version."""
|
|
3
|
+
import argparse,hashlib,json,os,pathlib,pwd,re,selectors,shutil,stat,subprocess,tempfile,time
|
|
4
|
+
p=argparse.ArgumentParser();p.add_argument('--leg',choices=['cli','hooks','permission','helper','tui','launcher'],required=True);p.add_argument('--bun',required=True);p.add_argument('--agy',required=True);p.add_argument('--expected-sha256',required=True);p.add_argument('--version',required=True,help='exact native version, for example 1.5.21');p.add_argument('--results-dir',required=True,help='existing directory outside the repository for producer JSON');p.add_argument('--execute',action='store_true');a=p.parse_args()
|
|
5
|
+
if not a.execute:raise SystemExit('Preparation only: root must review the wrapper and explicitly pass --execute in its owned Mac slot')
|
|
6
|
+
if not re.fullmatch(r'[0-9]+\.[0-9]+\.[0-9]+',a.version):raise SystemExit('--version must be an exact version')
|
|
7
|
+
if a.leg not in ['cli','hooks','permission','helper','launcher']:raise SystemExit('Only CLI/hooks/helper producers are enabled; Direct TUI producer remains preparation-only')
|
|
8
|
+
base=pathlib.Path(__file__).resolve().parent
|
|
9
|
+
realhome_typed=pwd.getpwuid(os.getuid()).pw_dir
|
|
10
|
+
realhome=pathlib.Path(realhome_typed).resolve()
|
|
11
|
+
wt=base.parents[2].resolve()
|
|
12
|
+
results=pathlib.Path(a.results_dir).resolve(strict=True)
|
|
13
|
+
if wt in results.parents or results==wt:raise SystemExit('--results-dir must be outside the repository')
|
|
14
|
+
bun=pathlib.Path(a.bun).resolve(strict=True);agy=pathlib.Path(a.agy).absolute()
|
|
15
|
+
info=agy.lstat()
|
|
16
|
+
if not stat.S_ISREG(info.st_mode) or stat.S_ISLNK(info.st_mode) or info.st_size>512*1024*1024 or hashlib.sha256(agy.read_bytes()).hexdigest()!=a.expected_sha256:raise SystemExit('Native binary fence refused before execution')
|
|
17
|
+
usertmp=subprocess.check_output(['/usr/bin/getconf','DARWIN_USER_TEMP_DIR'],text=True).strip()
|
|
18
|
+
root=pathlib.Path(tempfile.mkdtemp(prefix='ahub-801-controller-',dir=usertmp)).resolve(strict=True);root.chmod(0o700)
|
|
19
|
+
if realhome in root.parents:raise SystemExit('Owned controller root must be outside the real home')
|
|
20
|
+
for name in ['home','project','tmp','state','hub','amem','cache','data','xdg-state','bin']:(root/name).mkdir(mode=0o700)
|
|
21
|
+
(root/'bin/bun').symlink_to(bun)
|
|
22
|
+
(root/'bin/agy').write_text('#!/bin/sh\nexit 125\n');(root/'bin/agy').chmod(0o700)
|
|
23
|
+
env={'PATH':str(root/'bin')+':/usr/bin:/bin:/usr/sbin:/sbin','HOME':str(root/'home'),'XDG_CONFIG_HOME':str(root/'home/.config'),'XDG_CACHE_HOME':str(root/'cache'),'XDG_DATA_HOME':str(root/'data'),'XDG_STATE_HOME':str(root/'xdg-state'),'TMPDIR':str(root/'tmp')+'/','AGENTHUB_HOME':str(root/'hub'),'AMEM_HOME':str(root/'amem'),'AGENTHUB_STATE_DIR':str(root/'state'),'AGENTHUB_PROJECT_DIR':str(root/'project'),'AGY_CLI_DISABLE_AUTO_UPDATE':'1','LANG':'en_US.UTF-8','TERM':'xterm-256color','TASK801_ROOT':str(root),'TASK801_REAL_HOME':str(realhome),'TASK801_REAL_HOME_TYPED':realhome_typed,'TASK801_BUN':str(bun),'TASK801_AGY':str(agy),'TASK801_WT':str(wt),'TASK801_OUTPUT':str(base),'TASK801_VERSION':a.version,'TASK801_RESULTS':str(results),'TASK801_ORIGINALS':str(base/'originals'),'TASK801_PATH_BIN':str(root/'bin'),'TASK801_EXPECTED_SHA256':a.expected_sha256,'TASK801_EXECUTE':'root-approved'}
|
|
24
|
+
script={'cli':'cli-surface.ts','hooks':'native-hooks.ts','permission':'permission-new-functions.ts','helper':'tmux-helper-control.ts','launcher':'launcher-nonce.ts'}[a.leg]
|
|
25
|
+
def digest_file(file,limit):
|
|
26
|
+
st=file.lstat()
|
|
27
|
+
if not stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode) or st.st_size>limit:raise RuntimeError('Inventory source is not a bounded regular file')
|
|
28
|
+
h=hashlib.sha256()
|
|
29
|
+
with file.open('rb') as reader:
|
|
30
|
+
for block in iter(lambda:reader.read(1024*1024),b''):h.update(block)
|
|
31
|
+
after=file.lstat()
|
|
32
|
+
if (st.st_dev,st.st_ino,st.st_size,st.st_mtime_ns,st.st_ctime_ns)!=(after.st_dev,after.st_ino,after.st_size,after.st_mtime_ns,after.st_ctime_ns):raise RuntimeError('Inventory source changed')
|
|
33
|
+
return h.hexdigest()
|
|
34
|
+
def inventory():
|
|
35
|
+
configs={}
|
|
36
|
+
for name in ['antigravity-cli/settings.json','config/config.json','config/mcp_config.json','config/import_manifest.json','settings.json']:
|
|
37
|
+
file=realhome/'.gemini'/name
|
|
38
|
+
try:configs[name]={'present':True,'sha256':digest_file(file,524288)}
|
|
39
|
+
except FileNotFoundError:configs[name]={'present':False}
|
|
40
|
+
entries=[]
|
|
41
|
+
for file in sorted(agy.parent.iterdir()):
|
|
42
|
+
if file.name.startswith('agy'):
|
|
43
|
+
st=file.lstat();entries.append([file.name,st.st_mode,st.st_size,st.st_mtime_ns,st.st_ctime_ns])
|
|
44
|
+
return {'config':configs,'binarySha256':digest_file(agy,512*1024*1024),'binaryDirectoryCount':len(entries),'binaryDirectoryDigest':hashlib.sha256(json.dumps(entries,separators=(',',':')).encode()).hexdigest()}
|
|
45
|
+
def bounded_output(child,timeout):
|
|
46
|
+
selector=selectors.DefaultSelector();chunks={'stdout':bytearray(),'stderr':bytearray()};total=0;deadline=time.monotonic()+timeout
|
|
47
|
+
selector.register(child.stdout,selectors.EVENT_READ,'stdout');selector.register(child.stderr,selectors.EVENT_READ,'stderr')
|
|
48
|
+
try:
|
|
49
|
+
while selector.get_map():
|
|
50
|
+
remaining=deadline-time.monotonic()
|
|
51
|
+
if remaining<=0:raise subprocess.TimeoutExpired('owned-controller',timeout)
|
|
52
|
+
for key,_ in selector.select(min(remaining,1)):
|
|
53
|
+
data=os.read(key.fd,65536)
|
|
54
|
+
if not data:selector.unregister(key.fileobj);continue
|
|
55
|
+
total+=len(data)
|
|
56
|
+
if total>131072:raise RuntimeError('Controller output exceeded its bound; raw output withheld')
|
|
57
|
+
chunks[key.data].extend(data)
|
|
58
|
+
child.wait(timeout=max(0.001,deadline-time.monotonic()))
|
|
59
|
+
return bytes(chunks['stdout']),bytes(chunks['stderr'])
|
|
60
|
+
finally:selector.close()
|
|
61
|
+
def no_owned_survivors(receipt):
|
|
62
|
+
import re
|
|
63
|
+
output=subprocess.check_output(['/bin/ps','-axo','pid=,pgid=,stat=,lstart=,command='],env={'LC_ALL':'C','TZ':'UTC','PATH':'/usr/bin:/bin'},text=True,timeout=10)
|
|
64
|
+
rows=[]
|
|
65
|
+
for line in output.splitlines():
|
|
66
|
+
match=re.match(r'^\s*(\d+)\s+(\d+)\s+(\S+)\s+(\w{3} \w{3} [ \d]\d \d\d:\d\d:\d\d \d{4})\s+(.*)$',line)
|
|
67
|
+
if match and not match[3].startswith('Z') and str(root) in match[5]:return False
|
|
68
|
+
if match and not match[3].startswith('Z'):rows.append((int(match[1]),int(match[2]),match[4],hashlib.sha256(match[5].encode()).hexdigest()))
|
|
69
|
+
if not any(row[0]==os.getpid() for row in rows):raise RuntimeError('Final ownership inventory is unavailable')
|
|
70
|
+
for original in receipt.get('ownedBirths',[]):
|
|
71
|
+
if (original['pid'],original['pgid'],original['started'],original['commandHash']) in rows:return False
|
|
72
|
+
return True
|
|
73
|
+
child=None;clean=False;before=None;stage='inventory';out=b'';err=b''
|
|
74
|
+
source_sha=subprocess.check_output(['/usr/bin/git','-C',str(wt),'rev-parse','HEAD'],text=True).strip()
|
|
75
|
+
if not re.fullmatch(r'[0-9a-f]{40}',source_sha):raise SystemExit('Source head is unknown; run from a git checkout')
|
|
76
|
+
try:
|
|
77
|
+
before=inventory()
|
|
78
|
+
stage='producer';child=subprocess.Popen([str(bun),"--no-install",str(base/script)],cwd=root,env=env,stdin=subprocess.DEVNULL,stdout=subprocess.PIPE,stderr=subprocess.PIPE,start_new_session=True)
|
|
79
|
+
try:out,err=bounded_output(child,90)
|
|
80
|
+
except subprocess.TimeoutExpired:
|
|
81
|
+
child.terminate()
|
|
82
|
+
try:out,err=bounded_output(child,5)
|
|
83
|
+
except subprocess.TimeoutExpired:raise RuntimeError('Owned controller stop unconfirmed; retain its private root')
|
|
84
|
+
raise RuntimeError('Owned controller exceeded its bound; no native pass recorded')
|
|
85
|
+
rows=[]
|
|
86
|
+
for line in out.splitlines():
|
|
87
|
+
try:
|
|
88
|
+
value=json.loads(line)
|
|
89
|
+
if isinstance(value,dict) and 'cleanupConfirmed' in value:rows.append(value)
|
|
90
|
+
except (ValueError,UnicodeDecodeError):pass
|
|
91
|
+
if len(rows)!=1:raise RuntimeError('Closed producer receipt unavailable; raw output withheld')
|
|
92
|
+
stage='verification';result=rows[0];after=inventory();unchanged=before==after;gone=no_owned_survivors(result)
|
|
93
|
+
clean=result.get('cleanupConfirmed') is True and unchanged and gone
|
|
94
|
+
result.pop('ownedBirths',None)
|
|
95
|
+
print(json.dumps({'leg':a.leg,'controllerExit':child.returncode,'sourceSha':source_sha,'receipt':result,'stderrBytes':len(err),'inventoryBefore':before,'inventoryAfter':after,'inventoryUnchanged':unchanged,'ownedProcessesGone':gone}))
|
|
96
|
+
if not clean:raise RuntimeError('Producer/inventory/cleanup not confirmed; retain its private root')
|
|
97
|
+
if child.returncode!=0:
|
|
98
|
+
print(json.dumps({'leg':a.leg,'passed':False,'cause':'producer_requirements_failed','cleanupConfirmed':True}));raise SystemExit(1)
|
|
99
|
+
except Exception as failure:
|
|
100
|
+
if a.leg=='helper':
|
|
101
|
+
diagnostic=base/('tmux-helper-stderr-'+str(time.time_ns())+'.txt')
|
|
102
|
+
fd=os.open(diagnostic,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,0o600);os.write(fd,err);os.close(fd);print(json.dumps({"helperDiagnosticFile":diagnostic.name}))
|
|
103
|
+
diagnostics={'stage':stage,'failureClass':type(failure).__name__,'failureSha256':hashlib.sha256(str(failure).encode()).hexdigest(),'stdoutBytes':len(out),'stderrBytes':len(err),'stderrSha256':hashlib.sha256(err).hexdigest(),'pathRefusal':b'task801 command was not admitted' in err,'isolationRefusal':b'task801 isolated controller environment is required' in err,'syntaxFailure':b'SyntaxError' in err}
|
|
104
|
+
print(json.dumps({'leg':a.leg,'passed':False,'cause':'controller_or_producer_unconfirmed','rawOutputWithheld':True,'diagnostics':diagnostics}));raise SystemExit(1)
|
|
105
|
+
finally:
|
|
106
|
+
if child is not None and child.poll() is None:child.terminate()
|
|
107
|
+
if clean:shutil.rmtree(root)
|
|
108
|
+
else:print(json.dumps({'cleanupConfirmed':False,'ownedFixtureRetained':True}))
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
// Private task801 host harness. No native command runs on import.
|
|
2
|
+
import { spawn, type ChildProcess } from "node:child_process";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
import { existsSync, lstatSync, readFileSync, readdirSync, rmSync } from "node:fs";
|
|
5
|
+
import { dirname, isAbsolute, join, relative, resolve } from "node:path";
|
|
6
|
+
|
|
7
|
+
const env = process.env;
|
|
8
|
+
const ROOT = env.TASK801_ROOT!, REAL_HOME = env.TASK801_REAL_HOME!, AGY = env.TASK801_AGY!, BUN = env.TASK801_BUN!, WT = env.TASK801_WT!;
|
|
9
|
+
const within = (root: string, path: string) => { const name = relative(root, resolve(path)); return name === "" || name !== ".." && !name.startsWith("../") && !isAbsolute(name); };
|
|
10
|
+
export function assertEnvironment(): void {
|
|
11
|
+
if (env.TASK801_EXECUTE !== "root-approved" || !ROOT || !REAL_HOME || !AGY || !BUN || !WT || !isAbsolute(ROOT) || within(REAL_HOME, ROOT)) throw new Error("task801 isolated controller environment is required");
|
|
12
|
+
const root = lstatSync(ROOT);
|
|
13
|
+
if (!root.isDirectory() || root.isSymbolicLink() || root.uid !== process.getuid?.() || (root.mode & 0o777) !== 0o700) throw new Error("task801 owned root is invalid");
|
|
14
|
+
for (const name of ["HOME", "XDG_CONFIG_HOME", "XDG_CACHE_HOME", "XDG_DATA_HOME", "XDG_STATE_HOME", "TMPDIR", "AGENTHUB_HOME", "AMEM_HOME", "AGENTHUB_STATE_DIR", "AGENTHUB_PROJECT_DIR"]) if (!env[name] || !within(ROOT, env[name]!)) throw new Error("task801 isolation path is missing or outside the owned root");
|
|
15
|
+
if (!/^[0-9]+\.[0-9]+\.[0-9]+$/.test(env.TASK801_VERSION ?? "")) throw new Error("task801 exact native version is required");
|
|
16
|
+
if (env.AGY_CLI_DISABLE_AUTO_UPDATE !== "1" || !/^[a-f0-9]{64}$/.test(env.TASK801_EXPECTED_SHA256 ?? "")) throw new Error("task801 updater/binary fence is missing");
|
|
17
|
+
}
|
|
18
|
+
assertEnvironment();
|
|
19
|
+
const { stopOwnedProcess, trackGroup, readProcessTable, descendantsOf } = await import(join(WT, "src/hub/child-process.ts"));
|
|
20
|
+
const digest = (value: Buffer | string) => createHash("sha256").update(value).digest("hex");
|
|
21
|
+
let uncertain = false;
|
|
22
|
+
const active = new Set<ChildProcess>();
|
|
23
|
+
const ownedBirths: { pid: number; pgid: number; started: string; commandHash: string }[] = [];
|
|
24
|
+
const cancellation = new AbortController();
|
|
25
|
+
process.once("SIGTERM", () => cancellation.abort()); process.once("SIGINT", () => cancellation.abort());
|
|
26
|
+
function binary(): void {
|
|
27
|
+
const stat = lstatSync(AGY);
|
|
28
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 512 * 1024 * 1024 || digest(readFileSync(AGY)) !== env.TASK801_EXPECTED_SHA256) throw new Error("task801 native binary changed; stop the series");
|
|
29
|
+
}
|
|
30
|
+
export function removeOwnedRoot(path: string): void {
|
|
31
|
+
if (!within(ROOT, path) || active.size || uncertain) throw new Error("task801 cleanup is unconfirmed; preserve the owned fixture for inspection");
|
|
32
|
+
rmSync(path, { recursive: true, force: true });
|
|
33
|
+
}
|
|
34
|
+
function childEnvironment(input: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
|
|
35
|
+
const value = { ...input, PATH: env.PATH!, AGY_CLI_DISABLE_AUTO_UPDATE: "1" };
|
|
36
|
+
for (const name of ["HOME", "XDG_CONFIG_HOME", "TMPDIR", "AGENTHUB_HOME", "AGENTHUB_STATE_DIR", "AGENTHUB_PROJECT_DIR"]) if (!value[name] || !within(ROOT, value[name]!)) throw new Error("task801 native isolation path is invalid");
|
|
37
|
+
for (const name of ["AMEM_HOME", "XDG_CACHE_HOME", "XDG_DATA_HOME", "XDG_STATE_HOME"]) value[name] = env[name];
|
|
38
|
+
for (const name of Object.keys(value)) if (name.startsWith("ORCA_") || name.startsWith("AGENTHUB_RECOVERY_")) delete value[name];
|
|
39
|
+
if (value.GEMINI_API_KEY && value.GEMINI_API_KEY !== "fixture-key") throw new Error("task801 only fixture credentials are permitted");
|
|
40
|
+
if (value.GOOGLE_GEMINI_BASE_URL && !/^http:\/\/127\.0\.0\.1:[0-9]+$/.test(value.GOOGLE_GEMINI_BASE_URL)) throw new Error("task801 provider must be loopback");
|
|
41
|
+
return value;
|
|
42
|
+
}
|
|
43
|
+
export interface Run { code: number | null; stdout: string; stderr: string; cleanup: boolean; signalFallbackNeeded: boolean }
|
|
44
|
+
async function owned(command: string[], cwd: string, input: NodeJS.ProcessEnv, tty?: { steps: [number,string][]; initialMs: number }): Promise<Run> {
|
|
45
|
+
binary(); if (!within(ROOT, cwd) || cancellation.signal.aborted) throw new Error("task801 command was not admitted");
|
|
46
|
+
const nativeEnv = childEnvironment(input);
|
|
47
|
+
const child = spawn(command[0]!, command.slice(1), { cwd, env: nativeEnv, detached: true, stdio: ["pipe", "pipe", "pipe"] });
|
|
48
|
+
active.add(child); trackGroup(child);
|
|
49
|
+
let text = "", errors = "", bytes = 0, failed = false, fallback = false;
|
|
50
|
+
const take = (error: boolean, chunk: Buffer) => {
|
|
51
|
+
bytes += chunk.length;
|
|
52
|
+
if (bytes > (tty ? 400000 : 65536)) { failed = true; void stop().catch(() => { uncertain = true; }); return; }
|
|
53
|
+
if (error) errors += chunk.toString(); else text += chunk.toString();
|
|
54
|
+
};
|
|
55
|
+
child.stdout.on("data", chunk => take(false, chunk)); child.stderr.on("data", chunk => take(true, chunk));
|
|
56
|
+
let stopping: Promise<void> | undefined;
|
|
57
|
+
const stop = () => stopping ??= (async () => { fallback = child.exitCode === null && child.signalCode === null; await stopOwnedProcess(child, { group: true, termMs: 100, killMs: 1000 }); })();
|
|
58
|
+
const abort = () => { failed = true; void stop().catch(() => { uncertain = true; }); };
|
|
59
|
+
cancellation.signal.addEventListener("abort", abort, { once: true });
|
|
60
|
+
const timer = setTimeout(abort, 25000);
|
|
61
|
+
const done = new Promise<number | null>(accept => { child.once("error", () => { failed = true; accept(null); }); child.once("close", accept); });
|
|
62
|
+
const sleep = (ms: number) => new Promise<void>(accept => setTimeout(accept, ms));
|
|
63
|
+
const keys = tty ? (async () => {
|
|
64
|
+
await sleep(tty.initialMs);
|
|
65
|
+
for (const [ms, key] of tty.steps) {
|
|
66
|
+
if (child.exitCode !== null || child.signalCode !== null || failed || cancellation.signal.aborted) return;
|
|
67
|
+
if (key) child.stdin.write(key);
|
|
68
|
+
await sleep(ms);
|
|
69
|
+
}
|
|
70
|
+
})() : Promise.resolve();
|
|
71
|
+
try {
|
|
72
|
+
const observed = await readProcessTable();
|
|
73
|
+
if (!observed) throw new Error("task801 process ownership inventory is unavailable");
|
|
74
|
+
const direct = observed.find(row => row.pid === child.pid);
|
|
75
|
+
for (const row of [...(direct ? [direct] : []), ...(child.pid ? descendantsOf(observed, child.pid) : [])]) ownedBirths.push({ pid: row.pid, pgid: row.pgid, started: row.started, commandHash: digest(row.command) });
|
|
76
|
+
const code = await done;
|
|
77
|
+
await stop(); await keys;
|
|
78
|
+
if (command.at(-1) === "--version" && text.trim() !== env.TASK801_VERSION) throw new Error("task801 native version is not the required exact version");
|
|
79
|
+
binary();
|
|
80
|
+
active.delete(child);
|
|
81
|
+
return { code: failed ? null : code, stdout: text, stderr: errors, cleanup: true, signalFallbackNeeded: fallback };
|
|
82
|
+
} catch {
|
|
83
|
+
uncertain = true;
|
|
84
|
+
try { await stop(); active.delete(child); } catch { /* Retain the owner and fixture on an unconfirmed joined stop. */ }
|
|
85
|
+
throw new Error("task801 owned command cleanup or binary fence is unconfirmed");
|
|
86
|
+
}
|
|
87
|
+
finally { clearTimeout(timer); cancellation.signal.removeEventListener("abort", abort); }
|
|
88
|
+
}
|
|
89
|
+
export function runOwned(argv: string[], cwd: string, input: NodeJS.ProcessEnv, policy: string): Promise<Run> {
|
|
90
|
+
if (!policy.startsWith("(version 1)")) throw new Error("task801 native Seatbelt policy is required");
|
|
91
|
+
return owned(["/usr/bin/sandbox-exec", "-p", policy, ...argv], cwd, input);
|
|
92
|
+
}
|
|
93
|
+
export async function guardPolicy(policy: string, cwd: string, input: NodeJS.ProcessEnv): Promise<{ trueExit: 0; realHomeReadDenied: true; binaryWriteOpenDenied: true; network: "none" | "loopback-only" }> {
|
|
94
|
+
const truth = await runOwned(["/usr/bin/true"], cwd, input, policy);
|
|
95
|
+
if (truth.code !== 0) throw new Error("task801 Seatbelt profile is unavailable");
|
|
96
|
+
const names = ["antigravity-cli/settings.json", "config/config.json", "config/mcp_config.json", "config/import_manifest.json", "settings.json"];
|
|
97
|
+
const protectedFile = names.map(name => join(REAL_HOME, ".gemini", name)).find(path => existsSync(path));
|
|
98
|
+
if (!protectedFile) throw new Error("task801 named real-home guard cannot be established");
|
|
99
|
+
const read = await runOwned(["/usr/bin/python3", "-c", "import os,sys; f=os.open(sys.argv[1],os.O_RDONLY); os.close(f)", protectedFile], cwd, input, policy);
|
|
100
|
+
const write = await runOwned(["/usr/bin/python3", "-c", "import os,sys; f=os.open(sys.argv[1],os.O_WRONLY); os.close(f)", AGY], cwd, input, policy);
|
|
101
|
+
if (read.code === 0 || write.code === 0 || !read.stderr.includes("Operation not permitted") || !write.stderr.includes("Operation not permitted")) throw new Error("task801 real-home/binary guards were not established");
|
|
102
|
+
return { trueExit: 0, realHomeReadDenied: true, binaryWriteOpenDenied: true, network: policy.includes("network-outbound") ? "loopback-only" : "none" };
|
|
103
|
+
}
|
|
104
|
+
export function runOwnedTty(argv: string[], cwd: string, input: NodeJS.ProcessEnv, policy: string | undefined, initialMs = 0): Promise<Run> {
|
|
105
|
+
const steps: unknown = JSON.parse(env.TUI_KEYS ?? "[]");
|
|
106
|
+
if (!Array.isArray(steps) || steps.some(row => !Array.isArray(row) || row.length !== 2 || !Number.isSafeInteger(row[0]) || row[0] < 0 || row[0] > 5000 || typeof row[1] !== "string" || row[1].length > 256)) throw new Error("task801 TUI fixture steps are invalid");
|
|
107
|
+
if (!policy && argv[0] !== BUN) throw new Error("task801 unwrapped native TUI is refused");
|
|
108
|
+
return owned([BUN, join(env.TASK801_OUTPUT!, "pty-bridge.ts"), ...(policy ? ["/usr/bin/sandbox-exec", "-p", policy] : []), ...argv], cwd, input, { steps: steps as [number,string][], initialMs });
|
|
109
|
+
}
|
|
110
|
+
/** Nothing here serializes vendor output, paths, prompt text, hook payloads, provider bodies or nonce. */
|
|
111
|
+
export function safeReceipt(value: any): Record<string, unknown> {
|
|
112
|
+
const output: Record<string, unknown> = { cleanupConfirmed: !uncertain && active.size === 0, nativeSha256: env.TASK801_EXPECTED_SHA256, ownedBirths };
|
|
113
|
+
for (const key of ["realConfigUnchanged", "temporaryRootRemoved", "daemonStopped", "realUnchanged", "binUnchanged", "nonceInModelRequest"]) if (typeof value[key] === "boolean") output[key] = value[key];
|
|
114
|
+
for (const key of ["exit", "requests", "mcpCalls"]) if (typeof value[key] === "number" || value[key] === null) output[key] = value[key];
|
|
115
|
+
for (const key of ["version", "help", "acp", "new", "subcommands", "mcpList", "realHomeReadGuard", "binaryWriteOpenGuard"]) {
|
|
116
|
+
const row = value[key];
|
|
117
|
+
if (row && typeof row === "object") output[key] = { code: row.code, cleanup: row.cleanup === true, outputSha256: digest(row.stdout ?? ""), outputBytes: Buffer.byteLength(row.stdout ?? ""), stderrSha256: digest(row.stderr ?? ""), stderrBytes: Buffer.byteLength(row.stderr ?? ""), ...(key === "version" && /^[0-9]+\.[0-9]+\.[0-9]+$/.test((row.stdout ?? "").trim()) ? { observedVersion: row.stdout.trim() } : {}) };
|
|
118
|
+
}
|
|
119
|
+
const flags = ["--continue", "--conversation", "--disable-slash-commands", "--input-format", "--output-format", "--print", "--prompt-interactive", "--project", "--remote-control", "--sandbox"];
|
|
120
|
+
if (value.help) output.requiredFlags = Object.fromEntries(flags.map(flag => [flag, value.help.code === 0 && String((value.help.stdout ?? "") + (value.help.stderr ?? "")).includes(flag)]));
|
|
121
|
+
if (value.subcommands) output.subcommands = { code: value.subcommands.code, present: Object.fromEntries(["agent", "agents", "changelog", "help", "install", "mcp", "mic-serve", "models", "plugin", "plugins", "remote-control", "update", "acp"].map(name => [name, new RegExp(`(?:^|\\s)${name}(?:\\s|$)`).test(String((value.subcommands.stdout ?? "") + (value.subcommands.stderr ?? "")))])) };
|
|
122
|
+
output.expectedUnknownFlags = Object.fromEntries(["acp", "new"].map(name => [name, value[name]?.code === 2 && /flags? provided but not defined/.test(String(value[name]?.stderr))]));
|
|
123
|
+
if (value.mcpList) output.mcpNoServers = value.mcpList.code === 0 && String(value.mcpList.stdout).includes("No MCP servers configured");
|
|
124
|
+
if (typeof value.pinnedBunHelperAvailable === "boolean") output.pinnedBunHelperAvailable = value.pinnedBunHelperAvailable;
|
|
125
|
+
if (value.profileGuards) output.profileGuards = value.profileGuards;
|
|
126
|
+
if (value.permissionLeg) {
|
|
127
|
+
const pl = value.permissionLeg;
|
|
128
|
+
output.permissionLeg = { perCall: Array.isArray(pl.perCall) ? pl.perCall.slice(0, 3).map((call: any) => ({ name: ["run_workflow", "swarm", "update_steps"].includes(call.name) ? call.name : "other", hookPre: call.hookPre === true, hookPost: call.hookPost === true, refusalObserved: call.refusalObserved === true, providerRequestedOnce: call.providerRequestedOnce === true })) : [],
|
|
129
|
+
requirements: Object.fromEntries(["pinnedBunHelperAvailable", "nativeVersionExact", "newFunctionsDeclared", "providerAuthenticated", "loopbackOnlyGuards", "printExitedCleanly", "everyCallGatedBeforeEffect", "noFileEffect", "noExtraAgyProcess", "providerRequestsBounded"].map(name => [name, pl.requirements?.[name] === true])),
|
|
130
|
+
providerRequests: Number.isSafeInteger(pl.providerRequests) ? pl.providerRequests : null, hookRows: Number.isSafeInteger(pl.hookRows) ? pl.hookRows : null, extraAgyProcesses: Number.isSafeInteger(pl.extraAgyProcesses) ? pl.extraAgyProcesses : null,
|
|
131
|
+
fileEffects: pl.fileEffects === true, requirementsPassed: pl.requirementsPassed === true };
|
|
132
|
+
}
|
|
133
|
+
if (value.hookRequirements) {
|
|
134
|
+
const names = ["pinnedBunHelperAvailable", "nativeVersionExact", "mcpInventoryCompleted", "providerAuthenticated", "loopbackOnlyGuards", "printExitedCleanly", "mcpLifecycleObserved", "mcpTwoExactCalls", "nativeMcpCallShape", "nativeReadPathShape", "nativeReadResultObserved", "sixHookPhases", "sharedHookFields", "invocationHookFields", "toolHookFields", "injectSessionStartAccepted", "injectPreInvocationAccepted", "stopNoToolCall", "stopExecutionZero", "stopFullyIdle", "stopNoError", "providerEighteenDeclarations", "permissionModeRequestReview", "realConfigUnchanged"];
|
|
135
|
+
output.hookRequirements = Object.fromEntries(names.map(name => [name, value.hookRequirements[name] === true]));
|
|
136
|
+
output.hookProcedurePassed = names.every(name => value.hookRequirements[name] === true);
|
|
137
|
+
}
|
|
138
|
+
if (value.loopbackGuards) output.loopbackGuards = { allowedProviderConnect: value.loopbackGuards.allowedProviderConnect === true, otherOwnedLoopbackDenied: value.loopbackGuards.otherOwnedLoopbackDenied === true };
|
|
139
|
+
if (value.hookCounts) output.hookCounts = Object.fromEntries(["providerRequests", "mcpCalls", "nativeReadPre", "nativeReadPost", "hookRows", "nativeInitTools"].map(name => [name, Number.isSafeInteger(value.hookCounts[name]) && value.hookCounts[name] >= 0 ? value.hookCounts[name] : null]));
|
|
140
|
+
if (Array.isArray(value.unexpectedDeclarationNames)) output.unexpectedDeclarationNames = value.unexpectedDeclarationNames.slice(0, 8).map((name: unknown) => typeof name === "string" && /^[a-z][a-z0-9_]{0,39}$/.test(name) ? name : "other");
|
|
141
|
+
if (Array.isArray(value.providerDeclarationCounts)) output.providerDeclarationCounts = value.providerDeclarationCounts.slice(0, 13).map((count: unknown) => Number.isSafeInteger(count) && (count as number) >= 0 ? count : null);
|
|
142
|
+
if (Array.isArray(value.mcpDiagnostics)) {
|
|
143
|
+
const types = ["undefined", "null", "array", "object", "string", "number", "boolean"];
|
|
144
|
+
const keys = ["id", "verdict", "note", "ID", "Id", "Arguments", "arguments", "params", "parameters", "toolSummary", "toolAction"];
|
|
145
|
+
const projectShape = (shape: any) => ({ type: types.includes(shape?.type) ? shape.type : "other", keys: Array.isArray(shape?.keys) ? shape.keys.filter((key: unknown) => keys.includes(key as string)) : [], keyCount: Number.isSafeInteger(shape?.keyCount) ? shape.keyCount : null, unknownKeyCount: Number.isSafeInteger(shape?.unknownKeyCount) ? shape.unknownKeyCount : null,
|
|
146
|
+
...Object.fromEntries(["expectedKeys", "idNumberOne", "idStringOne", "verdictApproved", "noteFixtureOnly", "allExpectedValues"].map(key => [key, shape?.[key] === true])) });
|
|
147
|
+
const paramsKeys = ["name", "arguments", "Arguments", "id", "verdict", "note", "params", "parameters"];
|
|
148
|
+
output.mcpDiagnostics = value.mcpDiagnostics.slice(0,2).map((row: any) => ({ raw: projectShape(row.raw), parsedString: row.parsedString === true, decoded: projectShape(row.decoded),
|
|
149
|
+
paramsKeys: Array.isArray(row.paramsKeys) ? row.paramsKeys.filter((key: unknown) => paramsKeys.includes(key as string)) : [], paramsUnknownKeyCount: Number.isSafeInteger(row.paramsUnknownKeyCount) ? row.paramsUnknownKeyCount : null,
|
|
150
|
+
nativeArguments: { raw: projectShape(row.nativeArguments?.raw), parsedString: row.nativeArguments?.parsedString === true, decoded: projectShape(row.nativeArguments?.decoded) } }));
|
|
151
|
+
}
|
|
152
|
+
if (Array.isArray(value.nativeInitDiagnostics)) {
|
|
153
|
+
const types = ["absent", "other", "system", "init", "system_init", "system-init", "message", "assistant", "user", "tool", "tool_use", "tool_result", "tool_call", "result", "error", "session_start"];
|
|
154
|
+
const subtypes = ["absent", "other", "init", "success", "error", "permission", "session_start"];
|
|
155
|
+
const keys = ["type", "subtype", "session_id", "sessionId", "conversation_id", "conversationId", "tools", "permission_mode", "permissionMode", "model", "model_name", "version", "event", "data", "content", "message", "result", "error", "system", "init"];
|
|
156
|
+
const modes = ["absent", "other", "request-review", "request_review", "requestReview", "default", "ask", "accept-edits", "plan", "auto", "yolo", "bypassPermissions", "dontAsk"];
|
|
157
|
+
const places = ["event", "data", "message", "result", "system", "init"];
|
|
158
|
+
const location = (value: unknown) => typeof value === "string" && (value === "root" || value === "content[]" || value.split(".").length <= 2 && value.split(".").every(part => places.includes(part))) ? value : "other";
|
|
159
|
+
output.nativeInitDiagnostics = value.nativeInitDiagnostics.slice(0,128).map((row: any) => ({ location: location(row.location), type: types.includes(row.type) ? row.type : "other", subtype: subtypes.includes(row.subtype) ? row.subtype : "other", keys: Array.isArray(row.keys) ? row.keys.filter((key: unknown) => keys.includes(key as string)) : [], unknownKeyCount: Number.isSafeInteger(row.unknownKeyCount) ? row.unknownKeyCount : null,
|
|
160
|
+
permission_mode: modes.includes(row.permission_mode) ? row.permission_mode : "other", permissionMode: modes.includes(row.permissionMode) ? row.permissionMode : "other", toolCount: Number.isSafeInteger(row.toolCount) && row.toolCount >= 0 ? row.toolCount : null, initCandidate: row.initCandidate === true }));
|
|
161
|
+
}
|
|
162
|
+
const run = value.run;
|
|
163
|
+
if (run) output.run = { code: run.code, cleanup: run.cleanup === true, signalFallbackNeeded: run.signalFallbackNeeded === true, requestCount: run.requestCount, mcpCallCount: run.mcpCallCount, nonceInModelRequest: run.nonceInModelRequest === true, stdoutBytes: run.stdoutBytes, stdoutSha256: run.stdoutSha256, hookPhases: run.hookPhases };
|
|
164
|
+
if (Array.isArray(value.tools)) output.tools = value.tools.map((row: any) => {
|
|
165
|
+
let mcp: any[] = [], hooks: any[] = [];
|
|
166
|
+
try { mcp = row.mcpLog.trim().split("\n").filter(Boolean).map((line: string) => JSON.parse(line)); hooks = row.hookLog.trim().split("\n").filter(Boolean).map((line: string) => JSON.parse(line)); } catch {}
|
|
167
|
+
const phases = ["SessionStart", "PreInvocation", "PreToolUse", "PostToolUse", "PostInvocation", "Stop"];
|
|
168
|
+
return { code: row.code, phases: phases.filter(phase => hooks.some(event => event.phase === phase)), mcpCalls: ["hub_task_show", "hub_review"].filter(name => mcp.some(event => event.method === "tools/call" && event.params?.name === name)), fullyIdle: hooks.some(event => event.phase === "Stop" && event.input?.fullyIdle === true), stdoutSha256: digest(row.stdout ?? ""), stdoutBytes: Buffer.byteLength(row.stdout ?? "") };
|
|
169
|
+
});
|
|
170
|
+
return output;
|
|
171
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// Root-review control only. No native agent, provider, account or model is started here.
|
|
2
|
+
import { verifyInteractiveHelper } from "./tmux-session.ts";
|
|
3
|
+
const result = await verifyInteractiveHelper();
|
|
4
|
+
const passed = result.ready === true && result.normalExit === true && result.closedMarker === true;
|
|
5
|
+
console.log(JSON.stringify({ ...result, passed, agyStarted: false, cleanupConfirmed: true }));
|
|
6
|
+
if (!passed) process.exitCode = 1;
|
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
// Private, unexecuted task801 adapter. Every tmux request names only this fresh owned socket.
|
|
2
|
+
import { spawn, type ChildProcess } from "node:child_process";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
import { existsSync, lstatSync, watch } from "node:fs";
|
|
5
|
+
import { isAbsolute, join, relative } from "node:path";
|
|
6
|
+
import { assertEnvironment } from "./runtime.ts";
|
|
7
|
+
assertEnvironment();
|
|
8
|
+
const { trackGroup, stopOwnedProcess, readProcessTable, descendantsOf } = await import(join(process.env.TASK801_WT!, "src/hub/child-process.ts"));
|
|
9
|
+
const digest = (text: string) => createHash("sha256").update(text).digest("hex");
|
|
10
|
+
export interface InteractiveBirth { pid: number; pgid: number; started: string; commandHash: string }
|
|
11
|
+
export class OwnedInteractive {
|
|
12
|
+
readonly deadline: number;
|
|
13
|
+
readonly births: InteractiveBirth[] = [];
|
|
14
|
+
outputBytes = 0;
|
|
15
|
+
stderrBytes = 0;
|
|
16
|
+
nativePid: number | undefined;
|
|
17
|
+
nativeExitCode: number | undefined;
|
|
18
|
+
fallback = false;
|
|
19
|
+
cleanupConfirmed = false;
|
|
20
|
+
private readonly socket: string;
|
|
21
|
+
private readonly env: NodeJS.ProcessEnv;
|
|
22
|
+
private readonly cwd: string;
|
|
23
|
+
private readonly binary = process.env.TASK801_TMUX ?? "/opt/homebrew/bin/tmux";
|
|
24
|
+
private readonly server: ChildProcess;
|
|
25
|
+
private readonly clients = new Set<ChildProcess>();
|
|
26
|
+
private readonly listeners = new Set<() => void>();
|
|
27
|
+
private readonly timer: ReturnType<typeof setTimeout>;
|
|
28
|
+
private readonly interrupt = () => { this.fail("interactive_cancelled"); void this.stop().catch(() => {}); };
|
|
29
|
+
private readonly ready: Promise<void>;
|
|
30
|
+
private screen = "";
|
|
31
|
+
private revision = 0;
|
|
32
|
+
private failure: string | undefined;
|
|
33
|
+
private stopping = false;
|
|
34
|
+
private stopped: Promise<void> | undefined;
|
|
35
|
+
private refreshing: Promise<void> | undefined;
|
|
36
|
+
private dirty = false;
|
|
37
|
+
private input: Promise<void> = Promise.resolve();
|
|
38
|
+
private paneKnown = false;
|
|
39
|
+
private paneDead = false;
|
|
40
|
+
constructor(argv: readonly string[], cwd: string, env: NodeJS.ProcessEnv, totalMs = 80000) {
|
|
41
|
+
const root = process.env.TASK801_ROOT!;
|
|
42
|
+
const rel = relative(root, cwd);
|
|
43
|
+
if (!argv.length || argv.some(value => typeof value !== "string" || value.includes(String.fromCharCode(0))) || !isAbsolute(cwd) || rel === ".." || rel.startsWith("../") || isAbsolute(rel) || !Number.isSafeInteger(totalMs) || totalMs <= 0 || totalMs > 80000) throw Error("task801 tmux_arguments_refused");
|
|
44
|
+
this.socket = join(root, "t.sock"); this.cwd = cwd;
|
|
45
|
+
if (Buffer.byteLength(this.socket) >= 103 || existsSync(this.socket)) throw Error("task801 tmux_socket_not_fresh");
|
|
46
|
+
this.env = {};
|
|
47
|
+
for (const key of ["PATH", "HOME", "XDG_CONFIG_HOME", "XDG_CACHE_HOME", "XDG_DATA_HOME", "XDG_STATE_HOME", "TMPDIR", "AGENTHUB_HOME", "AMEM_HOME", "AGENTHUB_PROJECT_DIR", "AGENTHUB_STATE_DIR", "AGENTHUB_PEER_ID", "LANG", "LC_ALL", "TZ", "GIT_CONFIG_GLOBAL", "GIT_CONFIG_NOSYSTEM", "GIT_OPTIONAL_LOCKS", "GEMINI_API_KEY", "GOOGLE_GEMINI_BASE_URL"]) if (env[key] !== undefined) this.env[key] = env[key];
|
|
48
|
+
for (const key of Object.keys(env)) if (key.startsWith("TASK801_")) this.env[key] = env[key];
|
|
49
|
+
Object.assign(this.env, { TERM: "xterm-256color", TMUX_TMPDIR: root, AGY_CLI_DISABLE_AUTO_UPDATE: "1" });
|
|
50
|
+
if (this.env.GEMINI_API_KEY && this.env.GEMINI_API_KEY !== "fixture-key") throw Error("task801 fixture_credentials_required");
|
|
51
|
+
if (this.env.GOOGLE_GEMINI_BASE_URL && !/^http:\/\/127\.0\.0\.1:[0-9]+$/.test(this.env.GOOGLE_GEMINI_BASE_URL)) throw Error("task801 fixture_provider_required");
|
|
52
|
+
this.deadline = performance.now() + totalMs;
|
|
53
|
+
// -D keeps this server in the owned foreground process group, with exit-empty disabled.
|
|
54
|
+
this.server = this.launch(["-D", "-S", this.socket, "-f", "/dev/null"], false);
|
|
55
|
+
this.server.stdout!.on("data", (chunk: Buffer) => { this.outputBytes += chunk.length; if (this.outputBytes > 400000) this.fail("pty_output_bound"); });
|
|
56
|
+
this.server.once("close", () => { if (!this.stopping) this.fail("tmux_server_ended"); });
|
|
57
|
+
process.once("SIGTERM", this.interrupt); process.once("SIGINT", this.interrupt);
|
|
58
|
+
this.timer = setTimeout(() => { this.fail("tui_total_bound"); void this.stop().catch(() => {}); }, totalMs);
|
|
59
|
+
this.ready = this.initialize(argv);
|
|
60
|
+
void this.ready.catch(() => { this.fail("tmux_setup_failed"); });
|
|
61
|
+
}
|
|
62
|
+
private fail(code: string): void { this.failure ??= code; this.notify(); }
|
|
63
|
+
notify(): void { for (const listener of [...this.listeners]) listener(); }
|
|
64
|
+
checkpoint(): number { return this.revision; }
|
|
65
|
+
text(after = 0): string { return this.revision > after ? this.screen : ""; }
|
|
66
|
+
private launch(args: string[], client = true): ChildProcess {
|
|
67
|
+
const child = spawn(this.binary, args, { cwd: this.cwd, env: this.env, detached: true, stdio: ["pipe", "pipe", "pipe"] });
|
|
68
|
+
trackGroup(child); if (client) this.clients.add(child);
|
|
69
|
+
child.stdin!.on("error", () => { if (!this.stopping) this.fail("tmux_input_failed"); });
|
|
70
|
+
child.stderr!.on("data", (bytes: Buffer) => { this.stderrBytes += bytes.length; if (this.stderrBytes > 65536) this.fail("tmux_error_bound"); });
|
|
71
|
+
child.once("error", () => { if (!this.stopping) this.fail("tmux_start_failed"); });
|
|
72
|
+
// Kept in the owned set until joined cleanup, including already exited clients.
|
|
73
|
+
return child;
|
|
74
|
+
}
|
|
75
|
+
private async command(args: string[], cap = 65536): Promise<string> {
|
|
76
|
+
if (this.stopping || performance.now() >= this.deadline) throw Error("task801 tmux_command_not_admitted");
|
|
77
|
+
const child = this.launch(["-S", this.socket, "-f", "/dev/null", ...args]);
|
|
78
|
+
let output = "", size = 0, overflow = false;
|
|
79
|
+
child.stdout!.on("data", (chunk: Buffer) => { size += chunk.length; if (size <= cap) output += chunk.toString(); else overflow = true; });
|
|
80
|
+
let timeout: ReturnType<typeof setTimeout>;
|
|
81
|
+
try {
|
|
82
|
+
const code = await new Promise<number | null>((accept, reject) => {
|
|
83
|
+
timeout = setTimeout(() => { reject(Error("task801 tmux_command_bound")); }, Math.max(1, Math.min(5000, this.deadline - performance.now())));
|
|
84
|
+
child.once("error", () => reject(Error("task801 tmux_command_failed")));
|
|
85
|
+
child.once("close", accept);
|
|
86
|
+
});
|
|
87
|
+
if (code !== 0 || overflow) throw Error("task801 tmux_command_failed");
|
|
88
|
+
return output;
|
|
89
|
+
} finally { clearTimeout(timeout!); await stopOwnedProcess(child, { group: true }); this.clients.delete(child); }
|
|
90
|
+
}
|
|
91
|
+
private socketReady(): Promise<void> {
|
|
92
|
+
return new Promise((accept, reject) => {
|
|
93
|
+
let done = false;
|
|
94
|
+
const finish = (error?: Error) => { if (done) return; done = true; observer.close(); clearTimeout(timer); error ? reject(error) : accept(); };
|
|
95
|
+
const inspect = () => {
|
|
96
|
+
try {
|
|
97
|
+
const info = lstatSync(this.socket);
|
|
98
|
+
if (!info.isSocket() || info.isSymbolicLink() || info.uid !== process.getuid?.()) return finish(Error("task801 tmux_socket_invalid"));
|
|
99
|
+
finish();
|
|
100
|
+
} catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") finish(Error("task801 tmux_socket_invalid")); }
|
|
101
|
+
};
|
|
102
|
+
const observer = watch(process.env.TASK801_ROOT!, inspect);
|
|
103
|
+
const timer = setTimeout(() => finish(Error("task801 tmux_socket_unobserved")), Math.max(1, Math.min(5000, this.deadline - performance.now())));
|
|
104
|
+
observer.once("error", () => finish(Error("task801 tmux_socket_watch_failed"))); inspect();
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
private async initialize(argv: readonly string[]): Promise<void> {
|
|
108
|
+
await this.socketReady();
|
|
109
|
+
await this.command(["set-option", "-g", "default-terminal", "xterm-256color"]);
|
|
110
|
+
await this.command(["set-option", "-g", "status", "off"]);
|
|
111
|
+
await this.command(["set-window-option", "-g", "remain-on-exit", "on"]);
|
|
112
|
+
await this.command(["set-hook", "-g", "pane-died", "wait-for -S task801-ended"]);
|
|
113
|
+
// wait-for signal is retained by tmux even if a very short child exits before this waiter is scheduled.
|
|
114
|
+
const waiter = this.launch(["-S", this.socket, "-f", "/dev/null", "wait-for", "task801-ended"]);
|
|
115
|
+
waiter.stdout!.resume();
|
|
116
|
+
waiter.once("close", code => { if (!this.stopping) { if (code === 0) void this.refresh(); else this.fail("tmux_exit_signal_failed"); } });
|
|
117
|
+
const startedPid = (await this.command(["new-session", "-d", "-P", "-F", "#{pane_pid}", "-s", "fixture", "-c", this.cwd, "-x", "120", "-y", "40", "--", ...argv])).trim();
|
|
118
|
+
if (!/^[1-9][0-9]*$/.test(startedPid) || !Number.isSafeInteger(Number(startedPid))) throw Error("task801 tmux_initial_pane_pid_unknown");
|
|
119
|
+
this.nativePid = Number(startedPid);
|
|
120
|
+
this.paneKnown = true;
|
|
121
|
+
const control = this.launch(["-S", this.socket, "-f", "/dev/null", "-C", "attach-session", "-t", "fixture"]);
|
|
122
|
+
// Raw control-mode output is discarded; it only requests a fresh terminal-screen snapshot.
|
|
123
|
+
control.stdout!.on("data", (chunk: Buffer) => { this.outputBytes += chunk.length; if (this.outputBytes > 400000) this.fail("pty_output_bound"); else void this.refresh(); });
|
|
124
|
+
control.once("close", () => { if (!this.stopping && !this.paneDead) this.fail("tmux_control_ended"); });
|
|
125
|
+
await this.refresh(); await this.observeOwnership();
|
|
126
|
+
}
|
|
127
|
+
private refresh(): Promise<void> {
|
|
128
|
+
this.dirty = true;
|
|
129
|
+
if (this.refreshing) return this.refreshing;
|
|
130
|
+
if (this.stopping || !this.paneKnown) return Promise.resolve();
|
|
131
|
+
const work = (async () => {
|
|
132
|
+
while (this.dirty && !this.stopping) {
|
|
133
|
+
this.dirty = false;
|
|
134
|
+
const state = (await this.command(["display-message", "-p", "-t", "fixture:0.0", "#{pane_pid}:#{pane_dead}:#{pane_dead_status}"])).trim();
|
|
135
|
+
const match = /^([1-9][0-9]*|):([01]):([0-9]*)$/.exec(state);
|
|
136
|
+
if (!match) throw Error("task801 tmux_pane_state_invalid:"+JSON.stringify(state));
|
|
137
|
+
const dead = match[2] === "1", pid = match[1] ? Number(match[1]) : dead ? this.nativePid : undefined;
|
|
138
|
+
if (pid === undefined || !Number.isSafeInteger(pid) || (this.nativePid !== undefined && this.nativePid !== pid)) throw Error("task801 tmux_pane_replaced");
|
|
139
|
+
if (dead && (!match[3] || !Number.isSafeInteger(Number(match[3])))) throw Error("task801 tmux_exit_status_unknown");
|
|
140
|
+
const screen = await this.command(["capture-pane", "-p", "-t", "fixture:0.0"], 400000);
|
|
141
|
+
if (screen !== this.screen) { this.screen = screen; this.revision++; }
|
|
142
|
+
// Publish exit and its final screen together, including to external notify() callers.
|
|
143
|
+
this.nativePid = pid; this.paneDead = dead;
|
|
144
|
+
if (dead) this.nativeExitCode = Number(match[3]);
|
|
145
|
+
this.notify();
|
|
146
|
+
}
|
|
147
|
+
})();
|
|
148
|
+
this.refreshing = work;
|
|
149
|
+
void work.catch(error => { if (!this.stopping) this.fail(error instanceof Error&&error.message.startsWith("task801 ")?error.message.slice(8):"tmux_capture_failed"); }).finally(() => {
|
|
150
|
+
if (this.refreshing === work) this.refreshing = undefined;
|
|
151
|
+
if (this.dirty && !this.stopping && !this.failure) void this.refresh();
|
|
152
|
+
});
|
|
153
|
+
return work;
|
|
154
|
+
}
|
|
155
|
+
write(keys: string): void {
|
|
156
|
+
if (this.stopping || this.paneDead || this.failure || performance.now() >= this.deadline || Buffer.byteLength(keys) > 4096) throw Error("task801 interactive input is no longer admitted");
|
|
157
|
+
const parts: { literal?: string; key?: string }[] = [];
|
|
158
|
+
let literal = "";
|
|
159
|
+
const flush = () => { if (literal) { parts.push({ literal }); literal = ""; } };
|
|
160
|
+
const escape = String.fromCharCode(27);
|
|
161
|
+
for (let index = 0; index < keys.length;) {
|
|
162
|
+
const arrow = keys[index] === escape ? /^\[([ABCD])/.exec(keys.slice(index + 1)) : null;
|
|
163
|
+
if (arrow) { flush(); parts.push({ key: ({ A: "Up", B: "Down", C: "Right", D: "Left" } as Record<string, string>)[arrow[1]!]! }); index += 3; }
|
|
164
|
+
else if (keys[index] === "\r" || keys[index] === "\n") { flush(); parts.push({ key: "Enter" }); index++; }
|
|
165
|
+
else { if (keys.charCodeAt(index) < 32 || keys.charCodeAt(index) === 127) throw Error("task801 unsupported_terminal_key"); literal += keys[index++]; }
|
|
166
|
+
}
|
|
167
|
+
flush();
|
|
168
|
+
this.input = this.input.then(async () => {
|
|
169
|
+
await this.ready;
|
|
170
|
+
for (const part of parts) await this.command(["send-keys", "-t", "fixture:0.0", ...(part.key ? [part.key] : ["-l", "--", part.literal!])]);
|
|
171
|
+
});
|
|
172
|
+
void this.input.catch(() => this.fail("tmux_send_failed"));
|
|
173
|
+
}
|
|
174
|
+
async wait(check: () => boolean, timeoutMs = this.deadline - performance.now(), allowClosed = false): Promise<void> {
|
|
175
|
+
await new Promise<void>((accept, reject) => {
|
|
176
|
+
let done = false;
|
|
177
|
+
const finish = (code?: string) => { if (done) return; done = true; clearTimeout(timer); this.listeners.delete(inspect); code ? reject(Error(`task801 ${code}`)) : accept(); };
|
|
178
|
+
const inspect = () => {
|
|
179
|
+
if (this.failure || performance.now() >= this.deadline) return finish(this.failure ?? "tui_total_bound");
|
|
180
|
+
try { if (check()) return finish(); } catch { return finish("interactive_predicate_failed"); }
|
|
181
|
+
if ((this.paneDead || this.stopping) && !allowClosed) finish("interactive_ended_before_barrier");
|
|
182
|
+
};
|
|
183
|
+
const timer = setTimeout(() => finish("setup_barrier_unobserved"), Math.max(1, Math.min(timeoutMs, this.deadline - performance.now())));
|
|
184
|
+
this.listeners.add(inspect); inspect();
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
async observeOwnership(): Promise<void> {
|
|
188
|
+
const rows = await readProcessTable(); if (!rows) throw Error("task801 interactive ownership inventory unavailable");
|
|
189
|
+
for (const child of [this.server, ...this.clients]) {
|
|
190
|
+
const own = rows.find(row => row.pid === child.pid);
|
|
191
|
+
for (const row of [...(own ? [own] : []), ...(child.pid ? descendantsOf(rows, child.pid) : [])]) {
|
|
192
|
+
const commandHash = digest(row.command);
|
|
193
|
+
if (!this.births.some(birth => birth.pid === row.pid && birth.started === row.started && birth.commandHash === commandHash)) this.births.push({ pid: row.pid, pgid: row.pgid, started: row.started, commandHash });
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
async normalExit(): Promise<boolean> {
|
|
198
|
+
await this.wait(() => this.paneDead && this.nativeExitCode !== undefined, 45000, true);
|
|
199
|
+
return this.nativeExitCode === 0 && !this.fallback;
|
|
200
|
+
}
|
|
201
|
+
stop(): Promise<void> {
|
|
202
|
+
if (this.stopped) return this.stopped;
|
|
203
|
+
this.stopped = (async () => {
|
|
204
|
+
// Determine actual pane liveness before stopping the foreground server. Server cleanup alone is not fallback.
|
|
205
|
+
if (this.paneKnown && !this.paneDead) {
|
|
206
|
+
try { await this.refresh(); } catch { /* Unknown pane state remains unconfirmed and fallback is recorded. */ }
|
|
207
|
+
this.fallback ||= !this.paneDead;
|
|
208
|
+
}
|
|
209
|
+
this.stopping = true; this.notify();
|
|
210
|
+
await this.ready.catch(() => {});
|
|
211
|
+
await this.input.catch(() => {});
|
|
212
|
+
await this.refreshing?.catch(() => {});
|
|
213
|
+
await this.observeOwnership();
|
|
214
|
+
for (const child of [...this.clients]) await stopOwnedProcess(child, { group: true });
|
|
215
|
+
await stopOwnedProcess(this.server, { group: true });
|
|
216
|
+
const rows = await readProcessTable(); if (!rows) throw Error("task801 interactive final inventory unavailable");
|
|
217
|
+
if (this.births.some(birth => rows.some(row => row.pid === birth.pid && row.pgid === birth.pgid && row.started === birth.started && digest(row.command) === birth.commandHash))) throw Error("task801 tracked interactive process remains");
|
|
218
|
+
clearTimeout(this.timer); process.removeListener("SIGTERM", this.interrupt); process.removeListener("SIGINT", this.interrupt);
|
|
219
|
+
this.cleanupConfirmed = true;
|
|
220
|
+
})();
|
|
221
|
+
return this.stopped;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** Fixed stdin helper only, not native qualification. Root must explicitly enable its separate controller. */
|
|
226
|
+
export async function verifyInteractiveHelper(): Promise<Record<string, boolean | number>> {
|
|
227
|
+
const source = String.raw`const keepAlive=setTimeout(()=>process.exit(3),15000);process.stdout.write('TASK801_INTERACTIVE_READY\n');let pending='';for await(const chunk of Bun.stdin.stream()){pending+=new TextDecoder().decode(chunk);let end;while((end=pending.indexOf('\n'))>=0){const line=pending.slice(0,end).replace(/\r$/,'');pending=pending.slice(end+1);if(line==='q'){clearTimeout(keepAlive);process.stdout.write('TASK801_INTERACTIVE_CLOSED\n');process.exit(0);}}}clearTimeout(keepAlive);process.exit(2);`;
|
|
228
|
+
const session = new OwnedInteractive([process.env.TASK801_BUN!, "--no-install", "-e", source], process.env.AGENTHUB_PROJECT_DIR!, process.env, 25000);
|
|
229
|
+
try {
|
|
230
|
+
await session.wait(() => session.nativePid !== undefined && session.text().includes("TASK801_INTERACTIVE_READY"));
|
|
231
|
+
await session.observeOwnership(); const checkpoint = session.checkpoint(); session.write("q\r");
|
|
232
|
+
const normal = await session.normalExit();
|
|
233
|
+
return { ready: true, normalExit: normal, closedMarker: session.text(checkpoint).includes("TASK801_INTERACTIVE_CLOSED"), outputBytes: session.outputBytes };
|
|
234
|
+
} finally { await session.stop(); }
|
|
235
|
+
}
|