synth-code 0.0.1__py3-none-macosx_15_0_arm64.whl

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.
Files changed (110) hide show
  1. synth_code/__init__.py +0 -0
  2. synth_code/account.py +551 -0
  3. synth_code/account_http.py +86 -0
  4. synth_code/account_refusal.py +80 -0
  5. synth_code/accounting.py +148 -0
  6. synth_code/activity_grouping.py +149 -0
  7. synth_code/agent_panels.py +127 -0
  8. synth_code/approvals.py +397 -0
  9. synth_code/blobs.py +31 -0
  10. synth_code/cli.py +734 -0
  11. synth_code/client.py +413 -0
  12. synth_code/composer_delivery.py +139 -0
  13. synth_code/conversation.py +949 -0
  14. synth_code/daemon.py +34 -0
  15. synth_code/edition.py +306 -0
  16. synth_code/enrollment.py +304 -0
  17. synth_code/file_edit_facts.py +10 -0
  18. synth_code/freeze.py +234 -0
  19. synth_code/grant.py +59 -0
  20. synth_code/history.py +140 -0
  21. synth_code/history_generated.py +219 -0
  22. synth_code/history_wire.py +166 -0
  23. synth_code/image_input.py +109 -0
  24. synth_code/image_preview.py +105 -0
  25. synth_code/legacy_history.py +161 -0
  26. synth_code/live_turns.py +171 -0
  27. synth_code/model_picker.py +311 -0
  28. synth_code/native/manifest.json +1 -0
  29. synth_code/native/synth-code-runtime +0 -0
  30. synth_code/native.py +95 -0
  31. synth_code/oauth.py +284 -0
  32. synth_code/operator.py +116 -0
  33. synth_code/pack_source.py +65 -0
  34. synth_code/panel_request.py +291 -0
  35. synth_code/panels.py +40 -0
  36. synth_code/plugin_host.py +459 -0
  37. synth_code/protocol.py +35 -0
  38. synth_code/provider.py +313 -0
  39. synth_code/provider_fault.py +173 -0
  40. synth_code/provider_frames.py +571 -0
  41. synth_code/recommendation.py +324 -0
  42. synth_code/report.py +72 -0
  43. synth_code/research_events.py +44 -0
  44. synth_code/research_trace.py +449 -0
  45. synth_code/rex_view.py +58 -0
  46. synth_code/runtime_refusal.py +108 -0
  47. synth_code/schema/budgets.json +17 -0
  48. synth_code/schema/history-v2.json +1002 -0
  49. synth_code/session.py +291 -0
  50. synth_code/shoal.py +564 -0
  51. synth_code/side_panel.py +309 -0
  52. synth_code/skills.py +269 -0
  53. synth_code/slash.py +425 -0
  54. synth_code/source_view.py +135 -0
  55. synth_code/starter.json +13 -0
  56. synth_code/stdio.py +75 -0
  57. synth_code/stream.py +142 -0
  58. synth_code/subscriptions.py +267 -0
  59. synth_code/synth_authority.py +362 -0
  60. synth_code/synth_extra.py +32 -0
  61. synth_code/terminal.py +817 -0
  62. synth_code/terminal_journal.py +284 -0
  63. synth_code/terminal_layout.py +643 -0
  64. synth_code/terminal_surfaces.py +470 -0
  65. synth_code/terminal_viewport.py +125 -0
  66. synth_code/tool_render.py +86 -0
  67. synth_code/transcript_frames.py +212 -0
  68. synth_code/transcript_placement.py +63 -0
  69. synth_code/transcript_rows.py +456 -0
  70. synth_code/transport.py +243 -0
  71. synth_code/v001_history.py +468 -0
  72. synth_code/view.py +854 -0
  73. synth_code/views/__init__.py +93 -0
  74. synth_code/views/charts.py +196 -0
  75. synth_code/views/curses_adapter.py +116 -0
  76. synth_code/views/engine.py +170 -0
  77. synth_code/views/model.py +226 -0
  78. synth_code/views/primitives.py +270 -0
  79. synth_code/views/tiling.py +124 -0
  80. synth_code-0.0.1.dist-info/METADATA +50 -0
  81. synth_code-0.0.1.dist-info/RECORD +110 -0
  82. synth_code-0.0.1.dist-info/WHEEL +5 -0
  83. synth_code-0.0.1.dist-info/entry_points.txt +6 -0
  84. synth_code-0.0.1.dist-info/licenses/temper/LICENSE-APACHE +190 -0
  85. synth_code-0.0.1.dist-info/licenses/temper/LICENSE-MIT +21 -0
  86. synth_code-0.0.1.dist-info/licenses/temper/SOURCE.json +433 -0
  87. synth_code-0.0.1.dist-info/top_level.txt +2 -0
  88. synth_code_plugins/_sdk/__init__.py +19 -0
  89. synth_code_plugins/_sdk/callback_wire.py +240 -0
  90. synth_code_plugins/_sdk/callbacks.py +317 -0
  91. synth_code_plugins/_sdk/compliance.py +51 -0
  92. synth_code_plugins/_sdk/contracts.py +236 -0
  93. synth_code_plugins/_sdk/discovery.py +75 -0
  94. synth_code_plugins/_sdk/job_binding.py +71 -0
  95. synth_code_plugins/_sdk/lifecycle.py +50 -0
  96. synth_code_plugins/_sdk/lifecycle_generated.py +15 -0
  97. synth_code_plugins/_sdk/manifest.py +269 -0
  98. synth_code_plugins/_sdk/pack.py +332 -0
  99. synth_code_plugins/_sdk/push.py +98 -0
  100. synth_code_plugins/_sdk/records.py +26 -0
  101. synth_code_plugins/_sdk/registry.py +491 -0
  102. synth_code_plugins/_sdk/schemas.py +210 -0
  103. synth_code_plugins/_sdk/sources.py +230 -0
  104. synth_code_plugins/_sdk/surfaces.py +54 -0
  105. synth_code_plugins/_sdk/tools.py +172 -0
  106. synth_code_plugins/_sdk/worker_memory.py +49 -0
  107. synth_code_plugins/core/SKILL.md +6 -0
  108. synth_code_plugins/core/__init__.py +21 -0
  109. synth_code_plugins/core/plugin.toml +44 -0
  110. synth_code_plugins/core/source.py +18 -0
synth_code/cli.py ADDED
@@ -0,0 +1,734 @@
1
+ """Command line and return-to-run terminal for Synth Code."""
2
+
3
+ import argparse
4
+ import json
5
+ import os
6
+ import shlex
7
+ import sys
8
+ from functools import partial
9
+ from importlib.util import find_spec
10
+ from pathlib import Path
11
+ from uuid import uuid4
12
+
13
+ from .client import Client, bound_workspace
14
+ from .edition import (
15
+ FEATURE_COMMANDS,
16
+ FEATURE_SKILL_ACTIONS,
17
+ EditionUnavailable,
18
+ Feature,
19
+ feature_available,
20
+ require_feature,
21
+ require_skill_action,
22
+ )
23
+ from . import approvals, history
24
+ from .operator import preview
25
+ from .runtime_refusal import RuntimeUnreachable
26
+ from .synth_extra import SynthExtraMissing
27
+ from .session import connect, edit, message, starter, state_for, validate_message
28
+ from .terminal import terminal
29
+ from .view import WorkspaceViewBusy, run_curses, workspace_view
30
+
31
+
32
+ # CLI commands that need the optional ``synth`` extra, keyed to the module it provides.
33
+ _SYNTH_EXTRA_MODULES = {
34
+ "account": "synth_ai",
35
+ "login": "synth_ai",
36
+ "logout": "synth_ai",
37
+ }
38
+
39
+
40
+ def require_synth_extra(op):
41
+ """Refuse a command whose ``synth`` extra module is not installed, naming the extra."""
42
+ module = _SYNTH_EXTRA_MODULES.get(op)
43
+ if module is not None and find_spec(module) is None:
44
+ raise SynthExtraMissing(op)
45
+
46
+
47
+ def _view_command(
48
+ launcher, workspace, client, *, explicit_state, opened_workspace, view
49
+ ):
50
+ command = list(launcher or [str(Path(sys.argv[0]).absolute())])
51
+ command.extend(["--workspace", str(workspace), "--run", client.run])
52
+ if explicit_state:
53
+ command.extend(["--state", str(client.state)])
54
+ command.extend(["--wire-version", str(client.version)])
55
+ if not opened_workspace:
56
+ command.append("attach")
57
+ if view is not None and (not opened_workspace or view != "main"):
58
+ if opened_workspace:
59
+ command.append("open")
60
+ command.extend(["--view", view])
61
+ return command
62
+
63
+
64
+ class _ProductVersion(argparse.Action):
65
+ """Print the installed product version and release channel, then exit."""
66
+
67
+ def __init__(self, option_strings, dest, **kwargs):
68
+ super().__init__(option_strings, argparse.SUPPRESS, nargs=0, default=argparse.SUPPRESS)
69
+
70
+ def __call__(self, parser, namespace, values, option_string=None):
71
+ from .native import NativeRuntimeRefused, version_line
72
+
73
+ try:
74
+ line = version_line()
75
+ except NativeRuntimeRefused as refusal:
76
+ parser.exit(1, f"{refusal}\n")
77
+ print(line)
78
+ parser.exit(0)
79
+
80
+
81
+ def main(*, launcher=None):
82
+ try:
83
+ return _main(launcher=launcher)
84
+ except EditionUnavailable as refusal:
85
+ error = {"code": refusal.code, "feature": refusal.feature.value, "detail": str(refusal)}
86
+ print(json.dumps({"error": error}), file=sys.stderr)
87
+ raise SystemExit(2) from refusal
88
+ except RuntimeUnreachable as refusal:
89
+ print(json.dumps({"error": refusal.payload()}), file=sys.stderr)
90
+ raise SystemExit(2) from refusal
91
+ except SynthExtraMissing as refusal:
92
+ print(json.dumps({"error": refusal.payload()}), file=sys.stderr)
93
+ raise SystemExit(2) from refusal
94
+ except Exception as failure:
95
+ from .account_refusal import account_refusal
96
+
97
+ refusal = account_refusal(failure)
98
+ if refusal is None:
99
+ raise
100
+ print(json.dumps({"error": refusal}), file=sys.stderr)
101
+ raise SystemExit(2) from failure
102
+
103
+
104
+ def _global_options() -> argparse.ArgumentParser:
105
+ """Top-level options that take a value, shared by the parser and the command probe."""
106
+ options = argparse.ArgumentParser(add_help=False)
107
+ options.add_argument("--state", type=Path)
108
+ options.add_argument("--workspace", type=Path, default=Path.cwd())
109
+ options.add_argument("--run", default="main")
110
+ options.add_argument("--wire-version", dest="version", type=int, default=2)
111
+ options.add_argument("--resume", dest="resume_view", metavar="VIEW")
112
+ options.add_argument("--viewer-key", type=Path)
113
+ return options
114
+
115
+
116
+ def _omitted_commands() -> frozenset[str]:
117
+ return frozenset(
118
+ name for name, feature in FEATURE_COMMANDS.items() if not feature_available(feature)
119
+ )
120
+
121
+
122
+ def _refuse_omitted_command(argv, omitted) -> None:
123
+ """Refuse typed when the command names a feature this edition omits.
124
+
125
+ Runs before the full parser, which does not register omitted commands, and before
126
+ any import of the feature's modules.
127
+ """
128
+ probe = argparse.ArgumentParser(parents=[_global_options()], add_help=False)
129
+ probe.add_argument("op", nargs="?")
130
+ probe.add_argument("verb", nargs="?")
131
+ parsed = probe.parse_known_args(argv)[0]
132
+ if parsed.op in omitted:
133
+ raise EditionUnavailable(FEATURE_COMMANDS[parsed.op])
134
+ if parsed.op == "skill":
135
+ require_skill_action(parsed.verb)
136
+
137
+
138
+ def _main(*, launcher):
139
+ omitted = _omitted_commands()
140
+ _refuse_omitted_command(sys.argv[1:], omitted)
141
+ parser = argparse.ArgumentParser(parents=[_global_options()])
142
+ parser.add_argument("--version", action=_ProductVersion)
143
+ subs = parser.add_subparsers(dest="op")
144
+ opened = subs.add_parser("open")
145
+ opened.add_argument("--view", default="main")
146
+ opened.add_argument("--prompt", help="Send an initial message to Core")
147
+ attach = subs.add_parser("attach")
148
+ attach.add_argument("--view")
149
+ attach.add_argument("--event", type=int)
150
+ source_feed = subs.add_parser("source-feed")
151
+ source_feed.add_argument("plugin")
152
+ source_feed.add_argument("source")
153
+ source_feed.add_argument("--endpoint")
154
+ source_feed.add_argument("--turn")
155
+ source_feed.add_argument("--tool-id")
156
+ source_view = subs.add_parser("source-view")
157
+ source_view.add_argument("--source", required=True)
158
+ source_view.add_argument("--view", required=True)
159
+ for op in ("start", "describe"):
160
+ subs.add_parser(op)
161
+ for op in ("trace", "inspect"):
162
+ sub = subs.add_parser(op)
163
+ sub.add_argument("--after", type=int, default=0)
164
+ archive = subs.add_parser("convert-v1-history", help="Save a read-only HTML transcript of a legacy run")
165
+ archive.add_argument("destination", type=Path)
166
+ public_archive = subs.add_parser(
167
+ "convert-v0.01-history", help="Save a read-only HTML transcript of a public v0.01 store"
168
+ )
169
+ public_archive.add_argument("store", type=Path)
170
+ public_archive.add_argument("destination", type=Path)
171
+ sub = subs.add_parser("propose")
172
+ for key in ("effect", "name", "content"):
173
+ sub.add_argument(key)
174
+ sub.add_argument("--before")
175
+ sub.add_argument(
176
+ "--action", choices=["create", "replace", "count_bytes"], default="create"
177
+ )
178
+ subs.add_parser("read").add_argument("name")
179
+ sub = subs.add_parser("search")
180
+ sub.add_argument("name")
181
+ sub.add_argument("query")
182
+ subs.add_parser("approvals").add_argument("--json", action="store_true")
183
+ sub = subs.add_parser("approve")
184
+ sub.add_argument("effect")
185
+ sub.add_argument("digest")
186
+ subs.add_parser("execute").add_argument("effect")
187
+ sub = subs.add_parser("record")
188
+ for key in ("id", "kind", "summary"):
189
+ sub.add_argument(key)
190
+ sub.add_argument("cause", type=int)
191
+ sub = subs.add_parser("configure")
192
+ sub.add_argument("profile", type=Path)
193
+ sub = subs.add_parser("turn")
194
+ sub.add_argument("id")
195
+ sub.add_argument("role")
196
+ sub.add_argument("cause", type=int)
197
+ sub = subs.add_parser("assess")
198
+ sub.add_argument("id")
199
+ sub.add_argument("constraint", type=int)
200
+ sub.add_argument("pair", type=Path)
201
+ sub = subs.add_parser("skills")
202
+ sub.add_argument("skill_workspace", type=Path)
203
+ sub.add_argument("--rex", action="store_true")
204
+ sub = subs.add_parser("swarm-start")
205
+ sub.add_argument("id")
206
+ sub.add_argument("cause", type=int)
207
+ sub.add_argument("ceiling")
208
+ sub.add_argument("question")
209
+ sub = subs.add_parser("swarm-result")
210
+ sub.add_argument("remote_run")
211
+ sub = subs.add_parser("index")
212
+ sub.add_argument("arguments", type=Path)
213
+ sub.add_argument("--id")
214
+ sub.add_argument("--cause", type=int, default=1)
215
+ subs.add_parser("account")
216
+ login = subs.add_parser("login")
217
+ login.add_argument("--device", action="store_true")
218
+ login.add_argument(
219
+ "--with-inkling",
220
+ action="store_true",
221
+ help="Authorize a bounded Inkling session",
222
+ )
223
+ if feature_available(Feature.INDEX):
224
+ login.add_argument(
225
+ "--with-index",
226
+ action="store_true",
227
+ help="Request Index read and search access",
228
+ )
229
+ login.add_argument("--ceiling-micros", type=int, default=50_000)
230
+ login.add_argument(
231
+ "--allow-paid",
232
+ action="store_true",
233
+ help="Allow paid or non-Free plan funding for Inkling",
234
+ )
235
+ login.add_argument(
236
+ "--renew",
237
+ action="store_true",
238
+ help="Renew OAuth consent and inference lease",
239
+ )
240
+ subs.add_parser("html")
241
+ for verb in ("logout", "snapshot", "export", "rpc"):
242
+ subs.add_parser(verb)
243
+ for verb in ("ask", "edit", "create"):
244
+ sub = subs.add_parser(verb)
245
+ sub.add_argument("subject")
246
+ sub.add_argument("text")
247
+ sub.add_argument("--id")
248
+ sub = subs.add_parser("skill")
249
+ sub.add_argument(
250
+ "verb",
251
+ choices=tuple(
252
+ verb
253
+ for verb in ("show", "read", "list", "search", "setup", "preview", "pin", "unpin")
254
+ if verb not in FEATURE_SKILL_ACTIONS or feature_available(FEATURE_SKILL_ACTIONS[verb])
255
+ ),
256
+ )
257
+ sub.add_argument("name", nargs="?")
258
+ sub = subs.add_parser("note")
259
+ for key in ("kind", "scope", "key"):
260
+ sub.add_argument(key)
261
+ sub.add_argument("expected", type=int)
262
+ sub.add_argument("text")
263
+ sub.add_argument("--id")
264
+ sub = subs.add_parser("documents")
265
+ sub.add_argument("scope")
266
+ sub.add_argument("--id")
267
+ sub.add_argument("--revision", type=int)
268
+ sub.add_argument("--after", default="")
269
+ sub = subs.add_parser("query")
270
+ sub.add_argument("--after", type=int, default=0)
271
+ sub.add_argument("--actor")
272
+ sub.add_argument("--turn")
273
+ sub.add_argument("--cause", type=int)
274
+ sub.add_argument("--until", type=int)
275
+ for verb in ("preview", "cancel", "resume-provider"):
276
+ subs.add_parser(verb).add_argument("subject")
277
+ sub = subs.add_parser("iterate")
278
+ sub.add_argument("game", choices=("nethack", "craftax_classic", "craftax_full"))
279
+ sub.add_argument("arm", choices=("core", "pair"))
280
+ sub.add_argument("id")
281
+ sub.add_argument("filename")
282
+ sub.add_argument("policy_sha")
283
+ sub.add_argument("public_summary", type=Path)
284
+ sub = subs.add_parser("end")
285
+ sub.add_argument("id")
286
+ sub.add_argument("--cancel", action="store_true")
287
+ sub = subs.add_parser("rex")
288
+ sub.add_argument("seq", type=int)
289
+ sub.add_argument("--session", required=True)
290
+ sub.add_argument("--block", required=True)
291
+ rex_view = subs.add_parser("rex-view").add_subparsers(dest="action", required=True)
292
+ rex_open = rex_view.add_parser("open")
293
+ for field in ("effect_id", "source_id", "view_id", "session_id", "parent_block_id", "expected_label"):
294
+ rex_open.add_argument(field)
295
+ for action in ("lookup", "close"):
296
+ rex_view.add_parser(action).add_argument("effect_id")
297
+ sub = subs.add_parser("steer")
298
+ sub.add_argument("id")
299
+ sub.add_argument("message")
300
+ sub.add_argument("--operation", default=None)
301
+ sub = subs.add_parser("deny")
302
+ sub.add_argument("effect")
303
+ sub.add_argument("digest")
304
+ sub = subs.add_parser("spawn")
305
+ for field in ("id", "parent", "kind", "goal"):
306
+ sub.add_argument(field)
307
+ sub = subs.add_parser("close")
308
+ sub.add_argument("id")
309
+ sub.add_argument("result")
310
+ sub.add_argument("--cancel", action="store_true")
311
+ sub = subs.add_parser("publish")
312
+ sub.add_argument("notebook")
313
+ sub.add_argument("cursor", type=int)
314
+ for verb in ("artifact", "share", "unshare", "swarm-file"):
315
+ subs.add_parser(verb).add_argument("seq", type=int)
316
+ # Research commands exist only where the edition ships them; elsewhere argparse
317
+ # reports them as unknown choices.
318
+ research = require_feature(Feature.RESEARCH) if feature_available(Feature.RESEARCH) else None
319
+ if research is not None:
320
+ research.parsers(subs)
321
+ for verb in ("composition", "resume"):
322
+ subs.add_parser(verb)
323
+ sub = subs.add_parser("follow")
324
+ sub.add_argument("--after", type=int, default=0)
325
+ sub.add_argument("--until", type=int)
326
+ sub = subs.add_parser("checkpoint")
327
+ sub.add_argument("id")
328
+ sub.add_argument("through", type=int)
329
+ sub.add_argument("summary")
330
+ sub = subs.add_parser("viewer")
331
+ sub.add_argument("id")
332
+ sub.add_argument("file", type=Path)
333
+ sub.add_argument("--revoke", action="store_true")
334
+ sub = subs.add_parser("diagnostics")
335
+ sub.add_argument("directory", type=Path)
336
+ sub.add_argument("--after", type=int, default=0)
337
+ sub.add_argument("--ttl", type=int, default=3600)
338
+ sub = subs.add_parser("purge-diagnostics")
339
+ sub.add_argument("directory", type=Path)
340
+ # Commands whose feature this edition omits are not registered, so neither usage,
341
+ # choices nor help names them; _refuse_omitted_command already refused them typed.
342
+ for name in omitted:
343
+ del subs.choices[name]
344
+ args = vars(parser.parse_args())
345
+ prompt = args.pop("prompt", None)
346
+ if prompt is not None:
347
+ try:
348
+ validate_message(prompt)
349
+ except ValueError as error:
350
+ parser.error(f"--prompt: {error}")
351
+ viewer_key = args.pop("viewer_key")
352
+ workspace = args.pop("workspace").resolve()
353
+ state = args.pop("state")
354
+ client = Client(
355
+ state.resolve() if state else state_for(workspace),
356
+ args.pop("run"),
357
+ args.pop("version"),
358
+ viewer_key.read_text().strip() if viewer_key else None,
359
+ )
360
+ resume_view = args.pop("resume_view")
361
+ op = args.pop("op")
362
+ if resume_view is not None:
363
+ if op is not None:
364
+ raise ValueError("--resume requires no subcommand")
365
+ args["view"] = resume_view
366
+ op = "attach"
367
+ op = op or "open"
368
+ if client.viewer is not None and op not in (
369
+ "rpc",
370
+ "follow",
371
+ "query",
372
+ "export",
373
+ "html",
374
+ "panel",
375
+ "source-view",
376
+ ):
377
+ raise ValueError("Viewer scope is read-only")
378
+ require_synth_extra(op)
379
+ if op == "source-feed":
380
+ from .pack_source import attach_source
381
+
382
+ with client:
383
+ attach_source(client, **args)
384
+ return
385
+ if op == "source-view":
386
+ from .source_view import open_source_view
387
+
388
+ with client:
389
+ open_source_view(client, args["source"], args["view"])
390
+ return
391
+ if op == "convert-v1-history":
392
+ from .legacy_history import convert
393
+
394
+ archive = convert(client.state / "journal.sqlite", client.run, args["destination"])
395
+ print(json.dumps({"rows": archive.rows, "unreadable": archive.unreadable}))
396
+ return
397
+ if op == "convert-v0.01-history":
398
+ from .v001_history import V001Refusal, convert_v001
399
+
400
+ try:
401
+ public = convert_v001(args["store"], args["destination"])
402
+ except V001Refusal as refusal:
403
+ print(json.dumps({"error": {"code": refusal.code.value, "detail": refusal.detail}}), file=sys.stderr)
404
+ raise SystemExit(2) from refusal
405
+ print(json.dumps({
406
+ "rows": public.rows,
407
+ "unreadable": public.unreadable,
408
+ "unsupported": [
409
+ {"stream": r.stream, "sequence": r.sequence, "reason": r.reason.value, "label": r.label}
410
+ for r in public.unsupported
411
+ ],
412
+ }))
413
+ return
414
+ if research is not None and op in research.COMMANDS:
415
+ result = research.run(client, op, args)
416
+ print(result if isinstance(result, str) else json.dumps(result))
417
+ return
418
+ if op == "follow":
419
+ from .stream import follow
420
+
421
+ for row in follow(client, **args):
422
+ print(json.dumps(row), flush=True)
423
+ return
424
+ if op == "viewer":
425
+ from .stream import viewer
426
+
427
+ print(json.dumps(viewer(client, args["id"], args["file"], args["revoke"])))
428
+ return
429
+ if op == "diagnostics":
430
+ from .stream import diagnostic
431
+
432
+ print(
433
+ json.dumps(
434
+ diagnostic(client, args["directory"], args["after"], args["ttl"])
435
+ )
436
+ )
437
+ return
438
+ if op == "purge-diagnostics":
439
+ from .stream import purge
440
+
441
+ print(json.dumps({"removed": purge(args["directory"])}))
442
+ return
443
+ opened_workspace = op == "open"
444
+ if op == "open" or (op in ("ask", "edit", "create", "start") and not state):
445
+ connect(client, workspace, starter())
446
+ if op == "open":
447
+ op = "attach"
448
+ args.setdefault("view", "main")
449
+ if op in ("ask", "edit", "create"):
450
+ result = (
451
+ message(client, args["subject"], args["text"], args["id"])
452
+ if op == "ask"
453
+ else edit(
454
+ client,
455
+ args["id"] or uuid4().hex,
456
+ args["subject"],
457
+ args["text"],
458
+ create=op == "create",
459
+ )
460
+ )
461
+ print(json.dumps(result))
462
+ return
463
+ if op == "note":
464
+ from .session import revise
465
+
466
+ print(
467
+ json.dumps(
468
+ revise(
469
+ client,
470
+ args["kind"],
471
+ args["scope"],
472
+ args["key"],
473
+ args["expected"],
474
+ args["text"],
475
+ args["id"],
476
+ )
477
+ )
478
+ )
479
+ return
480
+ if op == "skill":
481
+ from .skills import RexUnavailable, action
482
+
483
+ try:
484
+ result = action(client, args["verb"], args["name"], workspace)
485
+ except RexUnavailable as refusal:
486
+ error = {"code": refusal.code, "stage": refusal.stage, "detail": str(refusal)}
487
+ print(json.dumps({"error": error}), file=sys.stderr)
488
+ raise SystemExit(2) from refusal
489
+ print(result if isinstance(result, str) else json.dumps(result))
490
+ return
491
+ if op == "rpc":
492
+ from .stdio import serve
493
+
494
+ serve(client, sys.stdin.buffer, sys.stdout)
495
+ return
496
+ if op in ("query", "export"):
497
+ from .history import export, query
498
+
499
+ for row in query(client, **args) if op == "query" else export(client):
500
+ print(json.dumps(row))
501
+ return
502
+ if op == "iterate":
503
+ iteration = require_feature(Feature.ITERATION).iteration
504
+ print(
505
+ json.dumps(
506
+ iteration(
507
+ client,
508
+ args["game"],
509
+ args["arm"],
510
+ args["id"],
511
+ args["filename"],
512
+ args["policy_sha"],
513
+ args["public_summary"].read_bytes(),
514
+ )
515
+ )
516
+ )
517
+ return
518
+ if op == "rex-view":
519
+ from .rex_view import custody
520
+
521
+ print(json.dumps(custody(client, **args)))
522
+ return
523
+ if op == "rex":
524
+ from .rex_view import show
525
+
526
+ print(json.dumps(show(client, **args)))
527
+ return
528
+ if op == "publish":
529
+ artifacts = require_feature(Feature.HOSTED_ARTIFACTS)
530
+ print(json.dumps(artifacts.publish(client, **args)))
531
+ return
532
+ if op in ("share", "unshare"):
533
+ artifacts = require_feature(Feature.HOSTED_ARTIFACTS)
534
+ print(json.dumps(artifacts.share(client, args["seq"], revoke=op == "unshare")))
535
+ return
536
+ if op == "swarm-file":
537
+ print(require_feature(Feature.HOSTED_SERVICES).swarm_file(client, args["seq"]))
538
+ return
539
+ if op == "artifact":
540
+ print(require_feature(Feature.HOSTED_ARTIFACTS).fetch(client, args["seq"]))
541
+ return
542
+ if op == "preview":
543
+ print(preview(client, args["subject"]))
544
+ return
545
+ if op == "approvals":
546
+ data = approvals.listing(client, history.events(client))
547
+ print(json.dumps(data) if args["json"] else approvals.format_listing(data))
548
+ return
549
+ if op == "cancel":
550
+ args = {"id": args["subject"]}
551
+ if op == "steer":
552
+ args["operation"] = args["operation"] or uuid4().hex
553
+ if op == "resume-provider":
554
+ op = "resume_provider"
555
+ args = {"provider": args["subject"]}
556
+ if op == "logout":
557
+ from .account import lifecycle
558
+
559
+ print(json.dumps(lifecycle("logout")))
560
+ return
561
+ if op == "search":
562
+ file = client.send("read", name=args["name"])
563
+ print(
564
+ json.dumps(
565
+ {
566
+ "sha256": file["sha256"],
567
+ "lines": [
568
+ i
569
+ for i, line in enumerate(file["content"].splitlines(), 1)
570
+ if args["query"] in line
571
+ ],
572
+ }
573
+ )
574
+ )
575
+ return
576
+ if op == "index":
577
+ import asyncio
578
+
579
+ index = require_feature(Feature.INDEX)
580
+ lookup, remember = index.lookup, index.remember
581
+ print(
582
+ json.dumps(
583
+ asyncio.run(
584
+ remember(
585
+ client,
586
+ json.loads(args["arguments"].read_text()),
587
+ args["id"],
588
+ args["cause"],
589
+ )
590
+ if args["id"]
591
+ else lookup(json.loads(args["arguments"].read_text()))
592
+ )
593
+ )
594
+ )
595
+ return
596
+ if op == "account":
597
+ if feature_available(Feature.HOSTED_SERVICES):
598
+ status = require_feature(Feature.HOSTED_SERVICES).account_status()
599
+ else:
600
+ from .account import account_status
601
+
602
+ status = account_status()
603
+ print(json.dumps(status))
604
+ return
605
+ if op == "login":
606
+ from .account import lifecycle
607
+
608
+ print(
609
+ json.dumps(
610
+ lifecycle(
611
+ "login",
612
+ device=args["device"],
613
+ account_only=not args["with_inkling"],
614
+ ceiling_micros=args["ceiling_micros"],
615
+ allow_paid=args["allow_paid"],
616
+ renew=args["renew"],
617
+ with_index=args.get("with_index", False),
618
+ )
619
+ )
620
+ )
621
+ return
622
+ if op == "swarm-start":
623
+ identity = args.pop("id")
624
+ seq = client.send(
625
+ "record",
626
+ id=identity + "-request",
627
+ kind="swarms.request",
628
+ cause=args.pop("cause"),
629
+ summary=json.dumps(args, sort_keys=True),
630
+ )
631
+ print(
632
+ json.dumps(
633
+ client.send(
634
+ "turn", id=identity, role="swarm-dispatch", cause=seq["seq"]
635
+ )
636
+ )
637
+ )
638
+ return
639
+ if op == "swarm-result":
640
+ services = require_feature(Feature.HOSTED_SERVICES)
641
+ print(json.dumps(services.remember_result(client, args["remote_run"])))
642
+ return
643
+ if op == "skills":
644
+ from .skills import setup
645
+
646
+ print(json.dumps(setup(args["skill_workspace"], args["rex"])))
647
+ return
648
+ if op == "html":
649
+ from .report import report
650
+
651
+ events = []
652
+ while page := client.page(events[-1]["seq"] if events else 0):
653
+ events.extend(page)
654
+ print(report(events))
655
+ return
656
+ for field in ("profile", "pair"):
657
+ if field in args:
658
+ args[field] = json.loads(args[field].read_text())
659
+ if op == "attach":
660
+ workspace = bound_workspace(client)
661
+ os.environ.setdefault("ESCDELAY", "25")
662
+ while True:
663
+ reload_state = {}
664
+ try:
665
+ with workspace_view(client.state, client.run, args["view"]) as (
666
+ saved,
667
+ save,
668
+ ):
669
+ if args.get("event") is not None:
670
+ at = args["event"]
671
+ client.event(at)
672
+ saved = saved | {"event": at, "detail_offset": 0}
673
+ def save_for_reload(fields, retained=reload_state):
674
+ if args["view"] is None:
675
+ retained.update(fields)
676
+ save(fields)
677
+
678
+ next_run = run_curses(
679
+ partial(terminal, prompt=prompt, development=launcher is not None),
680
+ client, saved, save_for_reload, workspace,
681
+ mouse=True,
682
+ state_dir=client.state,
683
+ )
684
+ except WorkspaceViewBusy as exc:
685
+ command = _view_command(
686
+ launcher,
687
+ workspace,
688
+ client,
689
+ explicit_state=state is not None,
690
+ opened_workspace=opened_workspace,
691
+ view=f"terminal-{uuid4().hex[:12]}",
692
+ )
693
+ if args.get("event") is not None:
694
+ command.extend(["--event", str(args["event"])])
695
+ raise SystemExit(
696
+ f"{exc} Return to the original terminal or open a separate view:\n"
697
+ f"{shlex.join(command)}"
698
+ ) from exc
699
+ from .terminal_surfaces import TerminalExit
700
+
701
+ if next_run is TerminalExit.RELOAD:
702
+ client.close()
703
+ view = args["view"]
704
+ if view is None:
705
+ view = f"terminal-{uuid4().hex[:12]}"
706
+ with workspace_view(client.state, client.run, view) as (_, save_reload):
707
+ save_reload(reload_state)
708
+ command = list(launcher or [str(Path(sys.argv[0]).absolute())])
709
+ command.extend([
710
+ "--workspace", str(workspace), "--state", str(client.state),
711
+ "--run", client.run, "--wire-version", str(client.version),
712
+ "--resume", view,
713
+ ])
714
+ os.execvp(command[0], command)
715
+ if next_run is None:
716
+ command = _view_command(
717
+ launcher,
718
+ workspace,
719
+ client,
720
+ explicit_state=state is not None,
721
+ opened_workspace=opened_workspace,
722
+ view=args["view"],
723
+ )
724
+ print(f"Resume this session:\n{shlex.join(command)}")
725
+ return
726
+ args["event"] = None
727
+ client = Client(client.state, next_run, client.version)
728
+ prompt = None
729
+ result = (
730
+ client.page(args["after"])
731
+ if op == "inspect"
732
+ else client.send(op, **args)
733
+ )
734
+ print(json.dumps(result, ensure_ascii=True))