managed_worker.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. """Private exec entry. No agent/config imports before adopted process authority.
  2. stdin is the owner's bounded bootstrap/control pipe; a duplicate of stdout is
  3. reserved for framed events before runtime imports redirect ordinary output.
  4. Neither assignment secrets nor launch credentials appear in argv or logs.
  5. """
  6. # Spawned as a bare ``sys.executable -m``: in a PM install that interpreter carries no dependencies
  7. # until hermes_bootstrap selects the committed environment, so it must be the first import.
  8. try:
  9. import hermes_bootstrap
  10. except ModuleNotFoundError as exc:
  11. if exc.name != "hermes_bootstrap":
  12. raise
  13. import contextlib
  14. import json
  15. import logging
  16. import os
  17. import re
  18. from pathlib import Path
  19. import sys
  20. import threading
  21. logger = logging.getLogger(__name__)
  22. MAX_FRAME = 4 * 1024 * 1024
  23. BOOTSTRAP_FIELDS = {'version', 'home', 'scope', 'policy', 'api_key', 'text', 'route', 'user_id', 'chat_id',
  24. 'turn_author', 'safe_mode', 'ignore_user_config'}
  25. # The bounded run_conversation fields a turn receipt keeps (outcome, exit reason, tokens, cost,
  26. # model): what the in-process projection commits and ``-z --usage-file`` reads.
  27. RESULT_FIELDS = ('final_response', 'failed', 'interrupted', 'completed', 'partial', 'error', 'turn_exit_reason',
  28. 'api_calls', 'model', 'provider', 'prompt_tokens', 'completion_tokens', 'total_tokens',
  29. 'cache_read_tokens', 'cache_write_tokens', 'reasoning_tokens',
  30. 'estimated_cost_usd', 'cost_status', 'cost_source', 'service_tier', 'failure_reason',
  31. 'session_id', 'requested_model', 'served_model', '_turn_input_tokens', '_turn_output_tokens',
  32. 'failure_retryable', 'failure_resets_at', 'billing_block', 'free_tier', 'usage_window_message')
  33. # The structured fields and their allowed keys: ``billing_block`` (``agent/billing_links.BillingBlock``
  34. # plus ``unverified``) and ``free_tier`` (``agent/turn_recovery._stamp_free_tier``). With
  35. # ``failure_reason``, ``failure_retryable`` and ``failure_resets_at`` they are what
  36. # ``agent.error_surface.build_error_surface_from_result`` reads for the owner's error card.
  37. BILLING_FIELDS = ('provider', 'provider_label', 'model', 'billing_url', 'is_nous', 'message', 'unverified')
  38. STRUCTURED_FIELDS = {'billing_block': BILLING_FIELDS, 'free_tier': ('kind', 'message')}
  39. def _scalar(value):
  40. return value is None or type(value) in (bool, int, float) or (isinstance(value, str) and len(value) <= 4096)
  41. def _structured(key, value):
  42. return isinstance(value, dict) and not set(value) - set(STRUCTURED_FIELDS[key]) and all(map(_scalar, value.values()))
  43. def result_frame(result):
  44. """Worker side: the receipt fields of ``run_conversation``'s result, scalars only, text bounded."""
  45. frame = {k: (v[:4096] if isinstance(v, str) and k != 'final_response' else v) for k, v in result.items()
  46. if k in RESULT_FIELDS and k not in STRUCTURED_FIELDS and (v is None or type(v) in (bool, int, float, str))}
  47. for key, fields in STRUCTURED_FIELDS.items():
  48. if isinstance(block := result.get(key), dict):
  49. frame[key] = {k: v[:4096] if isinstance(v, str) else v for k, v in block.items()
  50. if k in fields and (v is None or type(v) in (bool, int, float, str))}
  51. return frame
  52. def accept_result(result):
  53. """Owner side of the worker's result frame: ``(result, usage)`` in the in-process turn's shape
  54. (gateway projection: prompt/completion tokens as input/output), or ValueError."""
  55. if (not isinstance(result, dict) or set(result) - set(RESULT_FIELDS) or not isinstance(result.get('final_response'), str)
  56. or any(result.get(key) is not None and not _structured(key, result[key]) for key in STRUCTURED_FIELDS)
  57. or any(not _scalar(value) for key, value in result.items()
  58. if key != 'final_response' and key not in STRUCTURED_FIELDS)):
  59. raise ValueError('invalid_worker_result')
  60. accepted = dict(result)
  61. for key in STRUCTURED_FIELDS:
  62. if accepted.get(key) is None:
  63. # A failure other than a billing wall or a free-tier refusal carries no block.
  64. accepted.pop(key, None)
  65. turn_in, turn_out = accepted.pop('_turn_input_tokens', None), accepted.pop('_turn_output_tokens', None)
  66. if any(value is not None and (type(value) is not int or value < 0) for value in (turn_in, turn_out)):
  67. raise ValueError('invalid_worker_result')
  68. incoming, outgoing = accepted.pop('prompt_tokens', None), accepted.pop('completion_tokens', None)
  69. if incoming is None and outgoing is None:
  70. return accepted, {}
  71. usage = {'input_tokens': incoming or 0 if turn_in is None else turn_in,
  72. 'output_tokens': outgoing or 0 if turn_out is None else turn_out}
  73. usage['total_tokens'] = usage['input_tokens'] + usage['output_tokens']
  74. accepted.update(input_tokens=incoming or 0, output_tokens=outgoing or 0)
  75. return accepted, usage
  76. def read_frame(stream):
  77. line = stream.readline(MAX_FRAME + 1)
  78. if not line:
  79. raise EOFError('managed_worker_pipe_closed')
  80. if len(line) > MAX_FRAME or not line.endswith(b'\n'):
  81. raise ValueError('managed_worker_frame_too_large')
  82. frame = json.loads(line)
  83. if not isinstance(frame, dict):
  84. raise ValueError('invalid_managed_worker_frame')
  85. return frame
  86. def encode_frame(frame):
  87. data = json.dumps(frame, ensure_ascii=True, allow_nan=False, separators=(',', ':')).encode() + b'\n'
  88. if len(data) > MAX_FRAME:
  89. raise ValueError('managed_worker_frame_too_large')
  90. return data
  91. def validate_bootstrap(frame):
  92. if set(frame) - {'attachments_v1'} != BOOTSTRAP_FIELDS or frame['version'] != 1:
  93. raise ValueError('invalid_managed_worker_bootstrap')
  94. scope = frame['scope']
  95. fields = {'profile_id', 'session_id', 'execution_id', 'generation', 'pid', 'birth', 'secret', 'epoch'}
  96. if (not isinstance(scope, dict) or set(scope) != fields or scope['pid'] != os.getpid()
  97. or scope['profile_id'] != frame['home'] or not Path(frame['home']).is_absolute()
  98. or not isinstance(frame['policy'], dict)
  99. or any(not isinstance(frame[k], str) for k in ('text', 'route', 'user_id', 'chat_id'))
  100. or type(frame['safe_mode']) is not bool or type(frame['ignore_user_config']) is not bool
  101. or (frame['safe_mode'] and not frame['ignore_user_config'])
  102. or (frame['api_key'] is not None and not isinstance(frame['api_key'], str))):
  103. raise ValueError('invalid_managed_worker_bootstrap')
  104. from agent.turn_author import parse_turn_author
  105. if frame['turn_author'] is not None and (not isinstance(frame['turn_author'], dict)
  106. or parse_turn_author(frame['turn_author']) is None):
  107. raise ValueError('invalid_managed_worker_bootstrap')
  108. return frame
  109. def bind_worker_policy(frame):
  110. """Freeze the owner's assignment process-wide before any config/provider/agent import.
  111. The session's frozen config (never the live profile file) is what every config reader in
  112. this process returns afterwards, so a profile edit after creation cannot reshape it (MCP
  113. server definitions included). Ordinary sessions keep plugins, MCP and hooks; bypass sessions
  114. also bind the safe / ignore-user-config policy.
  115. """
  116. config = json.loads(frame['policy']['config_json'])
  117. if not frame['ignore_user_config']:
  118. from agent.safe_worker_policy import _bind_worker_config
  119. _bind_worker_config(config)
  120. return
  121. from agent.safe_worker_policy import _bind_safe_worker_policy
  122. _bind_safe_worker_policy(safe_mode=frame['safe_mode'], ignore_user_config=True, config=config)
  123. class WorkerChannel:
  124. def __init__(self, stream):
  125. self.stream = stream
  126. self.lock = threading.Lock()
  127. def send(self, kind, **payload):
  128. data = encode_frame({'type': kind, **payload})
  129. with self.lock:
  130. self.stream.write(data)
  131. self.stream.flush()
  132. _INTERRUPTED = object()
  133. # The owner's control pipe closing under a live worker means the owner died (a closing owner
  134. # signals the worker itself). The agent is interrupted at once; cooperative tools get this long.
  135. ORPHAN_GRACE_SECONDS = 10
  136. def _die_with_owner():
  137. """Then end this worker and, on POSIX, every descendant still in its process group: the owner
  138. spawns it as a group leader (``start_new_session``). Tools that open their own session (the
  139. terminal tool, background processes meant to outlive the turn) are not in it. Never a group
  140. this process does not lead."""
  141. def kill():
  142. if os.name != 'nt' and os.getpgrp() == os.getpid():
  143. import signal
  144. os.killpg(os.getpid(), signal.SIGKILL) # windows-footgun: ok — POSIX only
  145. os._exit(1)
  146. threading.Timer(ORPHAN_GRACE_SECONDS, kill).start()
  147. class WorkerControls:
  148. def __init__(self, channel, route):
  149. self.channel, self.route = channel, route
  150. self.agent = None
  151. self.stopped = threading.Event()
  152. self.finish = threading.Event()
  153. self.clarifications = {}
  154. self.lock = threading.Lock()
  155. self.reader = threading.Thread(target=self.read, name='managed-controls', daemon=True)
  156. self.reader.start()
  157. def stop(self):
  158. self.stopped.set()
  159. if self.agent is not None:
  160. from agent.interrupt_compat import request_hard_interrupt
  161. request_hard_interrupt(self.agent) # parity with the canonical Stop (SessionAuthority.interrupt)
  162. with self.lock:
  163. for state in self.clarifications.values():
  164. state['answer'] = _INTERRUPTED
  165. state['event'].set()
  166. def read(self):
  167. from tools.approval import resolve_gateway_approval
  168. try:
  169. while True:
  170. frame = read_frame(sys.stdin.buffer)
  171. if frame == {'type': 'stop'}:
  172. self.stop()
  173. continue
  174. if frame == {'type': 'finish'}:
  175. self.finish.set()
  176. return
  177. if (set(frame) != {'type', 'prompt_id', 'value'} or frame['type'] not in {'approval', 'clarify'}
  178. or not isinstance(frame['prompt_id'], str) or not isinstance(frame['value'], str)
  179. or len(frame['value']) > 16384):
  180. raise ValueError('invalid_managed_control')
  181. if frame['type'] == 'approval':
  182. if frame['value'] not in {'once', 'deny', 'session', 'always'}:
  183. raise ValueError('invalid_managed_control')
  184. resolve_gateway_approval(self.route, frame['value'], request_id=frame['prompt_id'])
  185. else:
  186. with self.lock:
  187. state = self.clarifications.get(frame['prompt_id'])
  188. if state is not None:
  189. state['answer'] = frame['value']
  190. state['event'].set()
  191. except (EOFError, OSError, ValueError) as exc:
  192. self.stop()
  193. self.finish.set()
  194. if not isinstance(exc, ValueError):
  195. _die_with_owner()
  196. def approval(self, data):
  197. from tools.approval import ack_gateway_approval
  198. fields = {'request_id', 'command', 'description', 'allow_session', 'allow_permanent', 'smart_denied', 'edit'}
  199. self.channel.send('approval', data={k: v for k, v in data.items() if k in fields})
  200. ack_gateway_approval(self.route, data['request_id'])
  201. def clarify(self, questions):
  202. """clarify_tool's batch contract: ``callback(questions) -> {answers, outcome, notice?}``.
  203. One owner prompt per question, stopping at the first that is interrupted or unanswered;
  204. an empty answer is a skip (``None``), as on the other surfaces. A finite turn (``chat -q`` /
  205. ``-z``, bound by worker_turn_scope) answers headless at once: its viewer cannot answer."""
  206. from gateway.session_finite import finite_clarify_reply, finite_turn_required
  207. if finite_turn_required() is True:
  208. return finite_clarify_reply()
  209. answers = {}
  210. reply = {'answers': answers, 'outcome': 'submitted'}
  211. for entry in questions:
  212. answer = self._ask(entry['question'], entry['choices'], entry['multi_select'])
  213. if answer is _INTERRUPTED:
  214. reply['outcome'] = 'cancelled'
  215. break
  216. if answer is None:
  217. reply['outcome'] = 'timed_out'
  218. break
  219. answers[entry['qid']] = answer.strip() or None
  220. return reply
  221. def _ask(self, question, choices, multi_select):
  222. import uuid
  223. from tools.clarify_gateway import get_clarify_timeout
  224. timeout = get_clarify_timeout() # the frozen worker config; <= 0 is unlimited, as on every surface
  225. prompt_id = uuid.uuid4().hex
  226. state = {'event': threading.Event(), 'answer': None}
  227. with self.lock:
  228. if self.stopped.is_set() or len(self.clarifications) >= 16:
  229. return _INTERRUPTED
  230. self.clarifications[prompt_id] = state
  231. try:
  232. self.channel.send('clarify', prompt_id=prompt_id, question=question,
  233. choices=list(choices or []), multi_select=bool(multi_select))
  234. state['event'].wait(timeout if timeout > 0 else None)
  235. return state['answer']
  236. finally:
  237. with self.lock:
  238. self.clarifications.pop(prompt_id, None)
  239. self.channel.send('prompt_settled', prompt_id=prompt_id)
  240. _OUTBOX_NAME = re.compile(r'[A-Za-z0-9_-]{1,200}')
  241. def outbox_dir(home, execution_id):
  242. """execution_id is a ledger key ('admission-worker:<hex>'); ':' is not a legal Windows path
  243. character, so the private outbox directory is a portable spelling of the same identity."""
  244. # A legacy-imported admission id is arbitrary text; never let it name a path outside
  245. # worker-outboxes (``../`` on POSIX, ``..\\`` or drive spellings on Windows).
  246. name = execution_id.replace(':', '-') if isinstance(execution_id, str) else ''
  247. if not _OUTBOX_NAME.fullmatch(name):
  248. raise ValueError('invalid_execution_id')
  249. return Path(home) / 'worker-outboxes' / name
  250. def discover_profile_mcp(policy):
  251. """The owner's MCP registry never crosses into this fresh interpreter; connect the profile's
  252. configured servers here, filtered to the frozen toolset selection, before tool discovery snapshots
  253. agent.tools. Safe mode keeps its deliberate no-MCP policy (discover_mcp_tools returns [])."""
  254. from tools.mcp_oauth import suppress_interactive_oauth
  255. from tools.mcp_tool_discovery import discover_mcp_tools
  256. with suppress_interactive_oauth():
  257. discover_mcp_tools(allowed_mcp_names=list(policy.toolsets))
  258. def retire_agent(agent):
  259. """A settled admission is a turn boundary, not the end of the session: the owner's
  260. in-process agent keeps its background processes, sandbox and browser between turns
  261. (release_clients), so the worker must too. Only memory extraction is turn-final work."""
  262. # A boundary task queued this turn (LLM-bound extraction) would be cancelled by the
  263. # provider shutdown's short drain; give it the same bounded head start cli_shutdown does.
  264. manager = getattr(agent, '_memory_manager', None)
  265. if manager is not None:
  266. manager.flush_pending(timeout=10)
  267. messages = getattr(agent, '_session_messages', None)
  268. agent.shutdown_memory_provider(messages if isinstance(messages, list) else None)
  269. agent.release_clients()
  270. def tool_frame(call_id, name, args, *result):
  271. """The callback arguments an in-process turn publishes from (executor-redacted display args,
  272. the result and its failure verdict); the owner builds the shared tool event from them."""
  273. frame = {'tool_call_id': str(call_id or ''), 'name': str(name or 'tool'), 'args': args if isinstance(args, dict) else {}}
  274. if result:
  275. from agent.display import _detect_tool_failure
  276. frame['result'] = result[0] if isinstance(result[0], str) else str(result[0])
  277. frame['is_error'] = bool(_detect_tool_failure(frame['name'], result[0])[0])
  278. from gateway.session_tool_events import bounded_args, bounded_result
  279. frame['args'] = bounded_args(frame['args'])
  280. if result:
  281. frame['result'] = bounded_result(result[0], frame['is_error'])
  282. return json.loads(json.dumps(frame, default=str))
  283. def execute(frame, channel):
  284. # The owner RPC below imports gateway/config modules (hermes_cli.config, providers,
  285. # hermes_cli.plugins) transitively; the policy must already be frozen when they load.
  286. bind_worker_policy(frame)
  287. from agent.runtime_session_store import RuntimeSessionStore, WorkerRPC
  288. scope = dict(frame['scope'])
  289. rpc = WorkerRPC(frame['home'])
  290. adopted = rpc('worker.adopt', **{k: v for k, v in scope.items() if k != 'epoch'})
  291. if adopted['owner_epoch'] != scope['epoch']:
  292. raise RuntimeError('stale_epoch')
  293. store = RuntimeSessionStore(rpc, scope, outbox_dir(frame['home'], scope['execution_id']), adopted)
  294. from gateway.session_kanban import bind_worker_context
  295. bind_worker_context(frame)
  296. # Background processes a previous admission of this session started outlive that worker
  297. # (F24); adopt them so process_manage in this turn can poll and kill them.
  298. from tools.process_registry import process_registry
  299. process_registry.recover_from_checkpoint()
  300. # Store construction binds the delegation ledger before tool discovery.
  301. from gateway.session_policy import restore_policy, policy_scope, register_worker_hooks
  302. policy = restore_policy(frame['policy'])
  303. register_worker_hooks(policy)
  304. discover_profile_mcp(policy)
  305. from run_agent import AIAgent
  306. from tools.approval import register_gateway_notify, unregister_gateway_notify
  307. from tools.approval_context import set_current_session_key
  308. set_current_session_key(frame['route'])
  309. os.environ['HERMES_GATEWAY_SESSION'] = '1'
  310. from gateway.session_worker_construct import checkpoint_agent_kwargs, construct_kwargs, routing_agent_kwargs
  311. construct = {'ephemeral_system_prompt': policy.skills_prompt, **construct_kwargs(frame)}
  312. controls = WorkerControls(channel, frame['route'])
  313. register_gateway_notify(frame['route'], controls.approval)
  314. agent = None
  315. try:
  316. with policy_scope(policy):
  317. agent = _construct_agent(frame, AIAgent, policy, model=policy.model, provider=policy.provider, base_url=policy.base_url,
  318. api_key=frame['api_key'], session_db=store, session_id=scope['session_id'],
  319. # delegate_task stays offered: each child is reserved by the owner under this
  320. # execution (agent/runtime_session_child.py) and retires with it.
  321. enabled_toolsets=list(policy.toolsets), max_iterations=policy.max_turns,
  322. reasoning_config=policy.reasoning_config,
  323. # ``tool`` / ``oneshot`` are storage labels for a CLI-surface agent (session_policy.SURFACES).
  324. platform=policy.platform if policy.source in ('tool', 'oneshot') else policy.source,
  325. gateway_session_key=frame['route'], user_id=frame['user_id'], chat_id=frame['chat_id'],
  326. skip_context_files=policy.ignore_rules, load_soul_identity=not policy.ignore_rules,
  327. skip_memory=policy.ignore_rules, skip_background_review=True, quiet_mode=True,
  328. pass_session_id=policy.pass_session_id,
  329. **checkpoint_agent_kwargs(policy.config()), **construct,
  330. **routing_agent_kwargs(policy.config(), policy.model, policy.provider, policy.base_url),
  331. stream_delta_callback=lambda text: channel.send('delta', text=text) if text else None,
  332. clarify_callback=controls.clarify,
  333. tool_start_callback=lambda call_id, name, args: channel.send('tool.start', **tool_frame(call_id, name, args)),
  334. tool_complete_callback=lambda call_id, name, args, result: channel.send('tool.complete',
  335. **tool_frame(call_id, name, args, result)))
  336. controls.agent = agent
  337. if controls.stopped.is_set():
  338. from agent.interrupt_compat import request_hard_interrupt
  339. request_hard_interrupt(agent)
  340. channel.send('ready', pid=os.getpid())
  341. history = store.get_messages_as_conversation(scope['session_id'])
  342. from gateway.session_kanban import run_worker_turns
  343. if 'attachments_v1' in frame:
  344. from gateway.session_ingress_media import restore_attachments
  345. from agent.image_routing import build_native_content_parts
  346. media = restore_attachments(frame)
  347. content, skipped = build_native_content_parts(frame['text'], media['media_urls'])
  348. if skipped:
  349. raise ValueError('managed_attachment_unavailable')
  350. frame = {**frame, 'text': content}
  351. before = (getattr(agent, 'session_prompt_tokens', 0) or 0,
  352. getattr(agent, 'session_completion_tokens', 0) or 0)
  353. # Most failed results name no provider or model; the owner's error card needs the agent's.
  354. result = {'provider': getattr(agent, 'provider', None), 'model': getattr(agent, 'model', None),
  355. **run_worker_turns(agent, frame, history)}
  356. result['_turn_input_tokens'] = max(0, (getattr(agent, 'session_prompt_tokens', 0) or 0) - before[0])
  357. result['_turn_output_tokens'] = max(0, (getattr(agent, 'session_completion_tokens', 0) or 0) - before[1])
  358. retire_agent(agent)
  359. agent = None
  360. # The auto-title thread bills through this store from a daemon thread; a title landing
  361. # after execution.finish is a stale_generation write that fails the close-time flush.
  362. from agent.title_generator import wait_for_title_upgrades
  363. wait_for_title_upgrades()
  364. store.flush_token_counts()
  365. if result.get('final_response') is None and (result.get('interrupted') or result.get('failed')):
  366. result['final_response'] = ''
  367. channel.send('result', result=result_frame(result))
  368. if not controls.finish.wait(30):
  369. raise ValueError('managed_finish_timeout')
  370. store.finish()
  371. channel.send('finished')
  372. finally:
  373. unregister_gateway_notify(frame['route'])
  374. if agent is not None:
  375. retire_agent(agent)
  376. try:
  377. store.close()
  378. finally:
  379. with contextlib.suppress(Exception): # a failing socket close never replaces the turn's outcome
  380. rpc.close()
  381. def _construct_agent(frame, factory, policy, **kwargs):
  382. """Agent construction resolves the provider credentials; a Kanban attempt that fails here
  383. still books the one-shot exit mapping (quota wall 75, re-login 78) before the crash."""
  384. try:
  385. from gateway.session_worker_construct import worker_route
  386. return factory(**{**kwargs, **worker_route(policy, kwargs)})
  387. except Exception as exc:
  388. from gateway.session_kanban import record_start_failure
  389. record_start_failure(frame, exc)
  390. raise
  391. def hello():
  392. """Identity the owner verifies before it reserves: this interpreter's pid and birth plus
  393. the ancestor chain it observes. Launchers (uv's venv python.exe) put the owner's Popen
  394. handle one or two hops above; the owner, never this process, decides whether they match."""
  395. import psutil
  396. from hermes_cli.process_identity import worker_birth
  397. me = psutil.Process()
  398. return {'pid': me.pid, 'birth': worker_birth(me), 'ancestors': [p.pid for p in me.parents()[:3]]}
  399. def main():
  400. channel = WorkerChannel(os.fdopen(os.dup(sys.stdout.fileno()), 'wb', buffering=0)) # windows-footgun: ok — binary frames
  401. os.dup2(sys.stderr.fileno(), sys.stdout.fileno())
  402. # This process's own stderr only, never the channel. The owner drains it into the profile's
  403. # private managed-worker.log, redacting each line (patterns plus this worker's launch key and
  404. # assignment secret) before it reaches disk; this process never opens a profile log itself.
  405. if not logger.handlers:
  406. logger.addHandler(logging.StreamHandler(sys.stderr))
  407. logger.propagate = False
  408. try:
  409. channel.send('hello', **hello())
  410. frame = validate_bootstrap(read_frame(sys.stdin.buffer))
  411. execute(frame, channel)
  412. except Exception:
  413. # Runtime exceptions can contain credentials; the owner gets no raw traceback.
  414. logger.exception('managed worker failed')
  415. channel.send('error', reason='managed_worker_failed')
  416. return 1
  417. finally:
  418. channel.stream.close()
  419. return 0
  420. if __name__ == '__main__':
  421. raise SystemExit(main())