The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli): store finite `-q` / `-z` gateway runs as `oneshot`
Tekniumb6c58a725412
diff --git a/agent/managed_worker.py b/agent/managed_worker.pyindex 944511ab347..49e122bef77 100644--- a/agent/managed_worker.py+++ b/agent/managed_worker.py@@ -307,8 +307,8 @@ def execute(frame, channel):api_key=frame['api_key'], session_db=store, session_id=scope['session_id'],enabled_toolsets=list(policy.toolsets), max_iterations=policy.max_turns,reasoning_config=policy.reasoning_config,- # ``tool`` is a storage label for a CLI-surface agent (session_policy.SURFACES).- platform=policy.platform if policy.source == 'tool' else policy.source,+ # ``tool`` / ``oneshot`` are storage labels for a CLI-surface agent (session_policy.SURFACES).+ platform=policy.platform if policy.source in ('tool', 'oneshot') else policy.source,gateway_session_key=frame['route'], user_id=frame['user_id'], chat_id=frame['chat_id'],skip_context_files=policy.ignore_rules, load_soul_identity=not policy.ignore_rules,skip_memory=policy.ignore_rules, skip_background_review=True, quiet_mode=True,diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.tsindex 7c932ce87d9..2d2b9f5f2c5 100644--- a/apps/shared/src/gateway-contract.generated.ts+++ b/apps/shared/src/gateway-contract.generated.ts@@ -4684,7 +4684,7 @@ export interface GroupsDiscardResult {export interface CanonicalCreateParams {profile?: string | nullrequest_id?: string | null- source?: 'cli' | 'tui' | 'gui' | 'acp' | 'tool'+ source?: 'cli' | 'tui' | 'gui' | 'acp' | 'tool' | 'oneshot'cwd?: string | nullmodel?: string | nullprovider?: string | nulldiff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.jsonindex f849ab756e4..8719558e9ea 100644--- a/apps/shared/src/gateway-contract.openrpc.json+++ b/apps/shared/src/gateway-contract.openrpc.json@@ -8520,7 +8520,8 @@"tui","gui","acp",- "tool"+ "tool",+ "oneshot"],"title": "Source","type": "string"diff --git a/gateway/session_a2a.py b/gateway/session_a2a.pyindex c060ce57331..243edc6cd56 100644--- a/gateway/session_a2a.py+++ b/gateway/session_a2a.py@@ -55,8 +55,8 @@ def storage_source(db, source, session_id, fallback):receipt = local_receipt(db, source.chat_id)if session_id not in receipt.get('lineage', [receipt['session_id']]):raise RuntimeStoreError('admission_conflict')- # Producer labels (a2a, cron, kanban, bot_room, ``--source tool``) survive the refresh: pickers- # filter on them (kanban/tool hidden, cron in its own section). Interactive+ # Producer labels (a2a, cron, kanban, bot_room, ``--source tool``, finite ``oneshot`` runs) survive the+ # refresh: pickers filter on them (kanban/tool/oneshot hidden, cron in its own section). Interactive# surfaces keep the transport's ``local``, outside the state-owned stale-open sweeps keyed on cli/tui/acp.label = receipt['policy']['source']return fallback if label in {'cli', 'tui', 'gui', 'acp'} else labeldiff --git a/gateway/session_controls.py b/gateway/session_controls.pyindex 3ff123b13f1..be2c5fdfb6c 100644--- a/gateway/session_controls.py+++ b/gateway/session_controls.py@@ -330,8 +330,8 @@ class AuthorityConnection:raisecontinuerow = self.authority.db.get_session(sid)- # The human picker feed (TUI switcher): kanban workers and `--source tool` integrations- # are not conversations, as on every other picker (INTERNAL_LISTING_SOURCES).+ # The human picker feed (TUI switcher): kanban workers, `--source tool` integrations and+ # finite one-shot runs are not conversations, as on every other picker.if row.get('source') in INTERNAL_LISTING_SOURCES:continuesessions.append({'session_id': sid, 'id': sid, 'title': row.get('title') or '',diff --git a/gateway/session_group_controls.py b/gateway/session_group_controls.pyindex eec29523163..2bd347e7adf 100644--- a/gateway/session_group_controls.py+++ b/gateway/session_group_controls.py@@ -281,10 +281,13 @@ def _profiles(authority, actor, home, params):else:owner_filter, owner_params = 'user_id=? AND ', (actor.subject,)with authority.db._lock:+ from hermes_state_sessions import INTERNAL_LISTING_SOURCES+ hidden_sources = ','.join('?' * len(INTERNAL_LISTING_SOURCES))latest = authority.db._conn.execute(f"SELECT id FROM sessions WHERE {owner_filter}chat_id LIKE 'local-%' AND archived=0 "+ f"AND COALESCE(source,'') NOT IN ({hidden_sources}) ""ORDER BY COALESCE(last_activity_at,started_at) DESC LIMIT 1",- owner_params).fetchone()+ (*owner_params, *INTERNAL_LISTING_SOURCES)).fetchone()if latest:row['last_session'] = summary(authority.db.get_session(latest[0]))profiles = [row]diff --git a/gateway/session_policy.py b/gateway/session_policy.pyindex 94ed23a7ede..77e144a739f 100644--- a/gateway/session_policy.py+++ b/gateway/session_policy.py@@ -13,9 +13,10 @@ CREATE_FIELDS = frozenset({'request_id', 'source', 'cwd', 'model', 'toolsets','skills', 'checkpoints', 'accept_hooks', 'pass_session_id'})BYPASS_FIELDS = ('safe_mode', 'ignore_user_config')_ACTIVE_POLICY: ContextVar = ContextVar('local_session_policy', default=None)-# Creation label -> agent surface. ``tool`` (third-party integrations, ``hermes chat --source tool``) runs as-# the CLI but keeps its own stored label, so human pickers hide it (INTERNAL_LISTING_SOURCES).-SURFACES = {'cli': 'cli', 'tui': 'tui', 'gui': 'desktop', 'acp': 'acp', 'tool': 'cli'}+# Creation label -> agent surface. ``tool`` (third-party integrations, ``hermes chat --source tool``) and+# ``oneshot`` (finite ``chat -q`` / ``-z`` runs) run as the CLI but keep their own stored label, so human+# pickers hide them (INTERNAL_LISTING_SOURCES).+SURFACES = {'cli': 'cli', 'tui': 'tui', 'gui': 'desktop', 'acp': 'acp', 'tool': 'cli', 'oneshot': 'cli'}@dataclass(frozen=True)diff --git a/gateway/session_worker_delegation.py b/gateway/session_worker_delegation.pyindex bc08ccee0d4..581167033ca 100644--- a/gateway/session_worker_delegation.py+++ b/gateway/session_worker_delegation.py@@ -54,7 +54,7 @@ def _dispatch(db, conn, session_id, payload, *, execution_id, worker_pid, workersession = conn.execute('SELECT source,session_key FROM sessions WHERE id=?', (session_id,)).fetchone()# Only compute registrations are currently enabled. Native/child origins need# an owner-reserved source envelope, not worker-selected transport identities.- if session is None or session['source'] not in ('cli', 'tui', 'gui', 'tool'):+ if session is None or session['source'] not in ('cli', 'tui', 'gui', 'tool', 'oneshot'):raise RuntimeStoreError('unsupported_producer')if (payload['parent_session_id'] != session_idor payload['session_key'] != (session['session_key'] or '')diff --git a/hermes_cli/gateway_chat.py b/hermes_cli/gateway_chat.pyindex 11a97aa1b95..d25f2398599 100644--- a/hermes_cli/gateway_chat.py+++ b/hermes_cli/gateway_chat.py@@ -78,6 +78,14 @@ def _caller_cwd(args) -> str:async def run_gateway_chat(args, emitter=None):from hermes_cli.gateway_chat_view import GatewayChatView+ query = getattr(args, "query", None) or getattr(args, "q", None)+ oneshot_prompt = getattr(args, "oneshot", None)+ if isinstance(oneshot_prompt, str):+ query = oneshot_prompt+ quiet = bool(getattr(args, "quiet", False) or oneshot_prompt or emitter is not None)+ # Finite: answer one prompt and exit (-z, --oneshot, -Q, stream-json, or -q off a TTY).+ oneshot = bool(oneshot_prompt or getattr(args, "oneshot_exit", False) or quiet or+ (query and not (sys.stdin.isatty() and sys.stdout.isatty())))async with connect_gateway() as client:description = await client.rpc("runtime.describe")title = continue_title(args)@@ -101,8 +109,11 @@ async def run_gateway_chat(args, emitter=None):check_resume_policy(args, snapshot)else:contract = description.get("session_create", {})- source = getattr(args, "source", None) or "cli"- if source not in contract.get("sources", []):+ # Finite runs are stored as ``oneshot`` (hidden from human pickers, still CLI history);+ # an explicit ``--source`` always wins. A remote gateway predating the label stores ``cli``.+ sources = contract.get("sources", [])+ source = getattr(args, "source", None) or ("oneshot" if oneshot and "oneshot" in sources else "cli")+ if source not in sources:raise GatewayClientError(f"Gateway does not support source {source!r}")parameters = contract.get("parameters", [])policy = _requested_policy(args)@@ -127,13 +138,6 @@ async def run_gateway_chat(args, emitter=None):print("Session: " + snapshot["stored_session_id"], file=sys.stderr, flush=True)if emitter is not None:emitter.bind_session(snapshot["stored_session_id"])- query = getattr(args, "query", None) or getattr(args, "q", None)- oneshot_prompt = getattr(args, "oneshot", None)- if isinstance(oneshot_prompt, str):- query = oneshot_prompt- quiet = bool(getattr(args, "quiet", False) or oneshot_prompt or emitter is not None)- oneshot = bool(oneshot_prompt or getattr(args, "oneshot_exit", False) or quiet or- (query and not (sys.stdin.isatty() and sys.stdout.isatty())))view = GatewayChatView(client, snapshot, quiet=quiet, emitter=emitter,usage_file=getattr(args, "usage_file", None))view.unattended = isinstance(oneshot_prompt, str)diff --git a/tests/gateway/test_local_source_labels.py b/tests/gateway/test_local_source_labels.pyindex 2ab84523186..13f23e20805 100644--- a/tests/gateway/test_local_source_labels.py+++ b/tests/gateway/test_local_source_labels.py@@ -1,5 +1,5 @@"""A canonical local session keeps the source label it was created with, and human pickers hide the-non-conversation labels (``tool`` integrations) as on the classic surfaces."""+non-conversation labels (``tool`` integrations, finite ``oneshot`` runs) as on the classic surfaces."""from pathlib import Pathfrom types import SimpleNamespace@@ -51,3 +51,19 @@ async def test_source_tool_is_admitted_stored_and_hidden_from_pickers(tmp_path,await conn.close()authority.db.close()++async def test_finite_oneshot_sessions_stay_out_of_every_owner_picker(tmp_path, monkeypatch):+ authority, store = await _authority(tmp_path, monkeypatch)+ conn = AuthorityConnection(authority, SimpleNamespace(write=lambda frame: None), {'user_id': 'owner'})+ chat = await _create(conn, authority, store, 'cli', 'chat')+ oneshot = await _create(conn, authority, store, 'oneshot', 'finite')+ assert authority.db.get_session(oneshot)['source'] == 'oneshot'+ # The newest local row is the one-shot; the TUI switcher and the Bots roster preview skip it.+ authority.db.append_message(oneshot, 'user', 'scripted')+ listed = await conn.dispatch({'id': 9, 'method': 'session.list', 'params': {}})+ assert [row['id'] for row in listed['result']['sessions']] == [chat]+ profiles = await conn.dispatch({'id': 10, 'method': 'profiles.list', 'params': {}})+ assert profiles['result']['profiles'][0]['last_session']['id'] == chat+ await conn.close()+ authority.db.close()diff --git a/tests/hermes_cli/test_gateway_chat.py b/tests/hermes_cli/test_gateway_chat.pyindex 64da98aa855..905cd005b59 100644--- a/tests/hermes_cli/test_gateway_chat.py+++ b/tests/hermes_cli/test_gateway_chat.py@@ -95,6 +95,40 @@ async def test_creation_preserves_advertised_cwd_model_and_toolsets(monkeypatch,assert create["source"] == "cli" and create["request_id"]+async def test_finite_runs_create_oneshot_sessions_and_explicit_source_wins(monkeypatch, tmp_path):+ """Finite ``-q``/``-z`` runs are stored as ``oneshot`` (kept out of human pickers); ``--source``+ always wins, and a gateway that does not advertise ``oneshot`` still gets a plain ``cli`` run."""+ from contextlib import asynccontextmanager+ from hermes_cli import gateway_chat+ from hermes_cli.gateway_chat_view import GatewayChatView+ created, sources = [], ["cli", "tool", "oneshot"]++ class Peer:+ async def rpc(self, method, **params):+ if method == "runtime.describe":+ return {"session_create": {"sources": sources, "parameters": ["cwd", "request_id", "source"]}}+ created.append(params["source"])+ return {"stored_session_id": "stored"}++ @asynccontextmanager+ async def connected():+ yield Peer()++ async def rendered(self, query, *, oneshot):+ return 0++ monkeypatch.setattr(gateway_chat, "connect_gateway", connected)+ monkeypatch.setattr(GatewayChatView, "run", rendered)+ monkeypatch.chdir(tmp_path)+ for args in (argparse.Namespace(query="q", quiet=True), argparse.Namespace(oneshot="z"),+ argparse.Namespace(query="q", quiet=True, source="tool")):+ assert await gateway_chat.run_gateway_chat(args) == 0+ sources.remove("oneshot")+ assert await gateway_chat.run_gateway_chat(argparse.Namespace(query="q", quiet=True)) == 0+ assert created == ["oneshot", "oneshot", "tool", "cli"]++@pytest.mark.asyncioasync def test_rpc_preserves_notifications_and_errors():import asynciodiff --git a/tui_gateway/contracts/canonical_sessions.py b/tui_gateway/contracts/canonical_sessions.pyindex 93766cf9651..cc10f7e7a7b 100644--- a/tui_gateway/contracts/canonical_sessions.py+++ b/tui_gateway/contracts/canonical_sessions.py@@ -16,7 +16,7 @@ class CanonicalSessionParams(ProfileParams):class CanonicalCreateParams(ProfileParams):request_id: str | None = None- source: Literal['cli', 'tui', 'gui', 'acp', 'tool'] = 'cli'+ source: Literal['cli', 'tui', 'gui', 'acp', 'tool', 'oneshot'] = 'cli'cwd: str | None = Nonemodel: str | None = Noneprovider: str | None = None