pycodex-ws 0.6.0__tar.gz → 0.6.1__tar.gz

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 (109) hide show
  1. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/PKG-INFO +6 -2
  2. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/README.md +4 -0
  3. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/pyproject.toml +2 -2
  4. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/WORKSPACE_API.md +7 -4
  5. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/app.py +9 -22
  6. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/content_views.mjs +7 -7
  7. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/frontend/content_views.mjs +3 -4
  8. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/routes.py +9 -4
  9. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/workspaces.py +18 -2
  10. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/.gitignore +0 -0
  11. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/LICENSE +0 -0
  12. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/pycodex_router/__init__.py +0 -0
  13. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/pycodex_router/__main__.py +0 -0
  14. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/pycodex_router/browser.py +0 -0
  15. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/pycodex_router/client.py +0 -0
  16. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/pycodex_router/index.html +0 -0
  17. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/pycodex_router/protocol.py +0 -0
  18. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/pycodex_router/server.py +0 -0
  19. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/pycodex_ws/__init__.py +0 -0
  20. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/pycodex_ws/feishu_auth.py +0 -0
  21. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/pycodex_ws/feishu_card.py +0 -0
  22. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/pycodex_ws/feishu_connection.py +0 -0
  23. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/pycodex_ws/feishu_link.py +0 -0
  24. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/pycodex_ws/feishu_oauth.py +0 -0
  25. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/pycodex_ws/feishu_render.py +0 -0
  26. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/pycodex_ws/server_support.py +0 -0
  27. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/pycodex_ws/workspace_config.py +0 -0
  28. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/__init__.py +0 -0
  29. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/__main__.py +0 -0
  30. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/agent_access.py +0 -0
  31. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/content_views.LICENSE.txt +0 -0
  32. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/content_views.css +0 -0
  33. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/customization.py +0 -0
  34. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/editor.css +0 -0
  35. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/editor.mjs +0 -0
  36. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/frontend/.gitignore +0 -0
  37. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/frontend/build.mjs +0 -0
  38. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/frontend/composer.mjs +0 -0
  39. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/frontend/content_views.css +0 -0
  40. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/frontend/editor.css +0 -0
  41. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/frontend/editor.mjs +0 -0
  42. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/frontend/editor_context.mjs +0 -0
  43. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/frontend/package-lock.json +0 -0
  44. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/frontend/package.json +0 -0
  45. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/frontend/prompt_history.mjs +0 -0
  46. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/frontend/touch_selection.mjs +0 -0
  47. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/frontend/transcript.mjs +0 -0
  48. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/frontend/view_labels.mjs +0 -0
  49. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/CONTRIBUTING.md +0 -0
  50. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/README.md +0 -0
  51. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/clock-ticks/README.md +0 -0
  52. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/clock-ticks/preview-mobile.png +0 -0
  53. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/clock-ticks/preview.html +0 -0
  54. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/clock-ticks/preview.png +0 -0
  55. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/clock-ticks/source/custom.css +0 -0
  56. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/clock-ticks/source/custom.js +0 -0
  57. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/clock-ticks/source/fixture.mjs +0 -0
  58. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/clock-ticks/source/verify.mjs +0 -0
  59. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/consecutive-tool-groups/README.md +0 -0
  60. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/consecutive-tool-groups/preview-mobile.png +0 -0
  61. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/consecutive-tool-groups/preview.html +0 -0
  62. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/consecutive-tool-groups/preview.png +0 -0
  63. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/consecutive-tool-groups/source/fixture.mjs +0 -0
  64. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/consecutive-tool-groups/source/tool-groups.css +0 -0
  65. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/consecutive-tool-groups/source/tool-groups.js +0 -0
  66. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/consecutive-tool-groups/source/verify.mjs +0 -0
  67. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/exec-status/README.md +0 -0
  68. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/exec-status/preview-mobile.png +0 -0
  69. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/exec-status/preview.html +0 -0
  70. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/exec-status/preview.png +0 -0
  71. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/exec-status/source/custom.css +0 -0
  72. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/exec-status/source/custom.js +0 -0
  73. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/exec-status/source/fixture.mjs +0 -0
  74. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/exec-status/source/verify.mjs +0 -0
  75. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/reasoning-display/README.md +0 -0
  76. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/reasoning-display/preview-mobile.png +0 -0
  77. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/reasoning-display/preview.html +0 -0
  78. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/reasoning-display/preview.png +0 -0
  79. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/reasoning-display/source/custom.css +0 -0
  80. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/reasoning-display/source/custom.js +0 -0
  81. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/reasoning-display/source/fixture.mjs +0 -0
  82. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/reasoning-display/source/verify.mjs +0 -0
  83. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/session-tips/README.md +0 -0
  84. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/session-tips/preview-mobile.png +0 -0
  85. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/session-tips/preview.html +0 -0
  86. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/session-tips/preview.png +0 -0
  87. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/session-tips/source/custom.css +0 -0
  88. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/session-tips/source/custom.js +0 -0
  89. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/session-tips/source/fixture.mjs +0 -0
  90. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/session-tips/source/session-tips.js +0 -0
  91. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/session-tips/source/verify.mjs +0 -0
  92. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/tool-calls/README.md +0 -0
  93. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/tool-calls/preview-mobile.png +0 -0
  94. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/tool-calls/preview.html +0 -0
  95. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/tool-calls/preview.png +0 -0
  96. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/tool-calls/source/custom.css +0 -0
  97. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/tool-calls/source/custom.js +0 -0
  98. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/tool-calls/source/fixture.mjs +0 -0
  99. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/optional_features/tool-calls/source/verify.mjs +0 -0
  100. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/owned_process.py +0 -0
  101. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/runtime_info.py +0 -0
  102. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/session_api.py +0 -0
  103. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/session_view.py +0 -0
  104. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/sessions.py +0 -0
  105. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/sharing.py +0 -0
  106. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/view_sources.py +0 -0
  107. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/workspace.html +0 -0
  108. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/workspace_views.py +0 -0
  109. {pycodex_ws-0.6.0 → pycodex_ws-0.6.1}/workspace_server/workspaces.html +0 -0
@@ -1,11 +1,11 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: pycodex-ws
3
- Version: 0.6.0
3
+ Version: 0.6.1
4
4
  Summary: Browser workspace and optional Feishu integration for python-codex
5
5
  License-File: LICENSE
6
6
  Requires-Python: >=3.7
7
7
  Requires-Dist: pillow>=9.0.0
8
- Requires-Dist: python-codex==0.6.0
8
+ Requires-Dist: python-codex==0.6.1
9
9
  Requires-Dist: websockets<16,>=11
10
10
  Description-Content-Type: text/markdown
11
11
 
@@ -55,6 +55,10 @@ running sessions and unread replies. `/cd <directory>` changes the current
55
55
  session's working directory while idle; `/model`, `/resume`, `/compact` and
56
56
  other core session commands are also available.
57
57
 
58
+ Use **New session** for the default profile, or its **+** button to choose one.
59
+ Profiles reload when you open the chooser or create a session, so config changes
60
+ apply to new sessions without restarting the server. Existing sessions keep their configuration.
61
+
58
62
  Consecutive model reconnection diagnostics share one collapsed `Model retries`
59
63
  row per sequence. The summary shows the number of recorded retries, the latest
60
64
  attempt and its HTTP status when available. Expand it to read the original errors
@@ -44,6 +44,10 @@ running sessions and unread replies. `/cd <directory>` changes the current
44
44
  session's working directory while idle; `/model`, `/resume`, `/compact` and
45
45
  other core session commands are also available.
46
46
 
47
+ Use **New session** for the default profile, or its **+** button to choose one.
48
+ Profiles reload when you open the chooser or create a session, so config changes
49
+ apply to new sessions without restarting the server. Existing sessions keep their configuration.
50
+
47
51
  Consecutive model reconnection diagnostics share one collapsed `Model retries`
48
52
  row per sequence. The summary shows the number of recorded retries, the latest
49
53
  attempt and its HTTP status when available. Expand it to read the original errors
@@ -4,12 +4,12 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "pycodex-ws"
7
- version = "0.6.0"
7
+ version = "0.6.1"
8
8
  description = "Browser workspace and optional Feishu integration for python-codex"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.7"
11
11
  dependencies = [
12
- "python-codex==0.6.0",
12
+ "python-codex==0.6.1",
13
13
  "pillow>=9.0.0",
14
14
  "websockets>=11,<16",
15
15
  ]
@@ -40,14 +40,17 @@ Agent execution permissions, and does not replace Router authentication.
40
40
  `GET api/sessions` returns `{sessions, profiles, default_profile}`. `profiles`
41
41
  contains only names from the server's Codex config; no provider configuration
42
42
  or credentials are returned. The catalog combines adjacent `*.config.toml` files
43
- and embedded `[profiles.NAME]` tables and rejects duplicate names. It is loaded
44
- when the workspace is built. `default_profile` is the launch `--profile`, then
45
- the top-level config `profile`, or `null` for the base configuration.
43
+ and embedded `[profiles.NAME]` tables and rejects duplicate names. It is reloaded
44
+ on every catalog request and session creation; additions, edits and removals
45
+ take effect without restarting the server. Responses use `Cache-Control: no-store`.
46
+ `default_profile` is the launch `--profile`, then the current top-level config
47
+ `profile`, or `null` for the base configuration. Invalid catalog configuration
48
+ or duplicate names return HTTP 400 rather than a stale catalog.
46
49
  Each session list entry includes its effective `profile` name or `null`.
47
50
 
48
51
  `POST api/sessions` accepts `{title?, prompt?, profile?, name?}`. Title and prompt are
49
52
  strings and default to empty. Profile is a string name; omission or `null` uses
50
- the server default. An unknown name returns HTTP 400; an invalid field type
53
+ the current server default. An unknown or removed name returns HTTP 400; an invalid field type
51
54
  returns HTTP 422. An empty body still creates a default session.
52
55
  The selected profile configures both the model and Agent instructions; CLI
53
56
  overrides still apply. A nonempty prompt is submitted through Runtime.
@@ -130,18 +130,6 @@ def build_parser() -> "argparse.ArgumentParser":
130
130
  default=None,
131
131
  help="Optional base URL for a chat-completions-backed vLLM server.",
132
132
  )
133
- parser.add_argument(
134
- "--use-chat-completion",
135
- default=False,
136
- action="store_true",
137
- help="Start a local responses compat server for this session.",
138
- )
139
- parser.add_argument(
140
- "--use-messages",
141
- default=False,
142
- action="store_true",
143
- help="Route through a downstream /v1/messages backend.",
144
- )
145
133
  return parser
146
134
 
147
135
 
@@ -358,9 +346,6 @@ def _build_workspace_entry(
358
346
  args: "argparse.Namespace",
359
347
  persist_callback: "typing.Union[typing.Callable[[], None], None]" = None,
360
348
  ) -> "WorkspaceEntry":
361
- selected = read_codex_config(args.config, args.profile)
362
- profiles = list_codex_profiles(args.config)
363
-
364
349
  def build_session(profile) -> "WorkspaceInteractiveSession":
365
350
  config = CodexConfig.from_env(
366
351
  args.config, profile, use_default_profile=False,
@@ -369,8 +354,6 @@ def _build_workspace_entry(
369
354
  config.provider,
370
355
  timeout_seconds=args.timeout_seconds,
371
356
  vllm_endpoint=args.vllm_endpoint,
372
- use_chat_completion=args.use_chat_completion or None,
373
- use_messages=args.use_messages,
374
357
  )
375
358
  if bootstrap.owned_server is not None:
376
359
  atexit.register(bootstrap.owned_server.stop)
@@ -398,17 +381,21 @@ def _build_workspace_entry(
398
381
  partial(build_session, profile), asyncio.get_running_loop()
399
382
  )
400
383
 
384
+ def load_profiles():
385
+ selected = read_codex_config(args.config, args.profile)
386
+ factories = {
387
+ name: partial(session_factory, name)
388
+ for name in list_codex_profiles(args.config)
389
+ }
390
+ return factories, selected["profile"]
391
+
401
392
  return WorkspaceEntry(
402
393
  definition=definition,
403
394
  manager=WorkspaceSessionManager(
404
395
  partial(session_factory, None),
405
396
  definition.state_path,
406
397
  persist_callback=persist_callback,
407
- profile_factories={
408
- name: partial(session_factory, name)
409
- for name in profiles
410
- },
411
- default_profile=selected["profile"],
398
+ profile_loader=load_profiles,
412
399
  ),
413
400
  )
414
401
 
@@ -1,16 +1,16 @@
1
1
  // Generated by workspace_server/frontend/build.mjs. See content_views.LICENSE.txt.
2
- function V(l){function t(n){let r=n.lastIndexOf("/");return r<0?".":n.slice(0,r)||"/"}let e=new Map,i=l.map(n=>{let o=(n.kind==="diff"?n.title.split(" <-> "):[n.title]).map(h=>{let a=/^(?:([0-9a-f]{40}|[0-9a-f]{64})|.+ \(([0-9a-f]{40}|[0-9a-f]{64})\)):(.+)$/i.exec(h),u=a?a[3]:h,d=u.slice(u.lastIndexOf("/")+1);return e.has(d)||e.set(d,new Set),e.get(d).add(u),{path:u,name:d,revision:a?(a[1]||a[2]).slice(0,7):null}});return{view:n,sources:o}}),s=new Map;for(let n of e.values()){if(n.size<2)continue;let r=Array.from(n),o=r.map(h=>t(h).split("/"));r.forEach((h,a)=>{let u=1;for(;u<o[a].length&&o.some((d,m)=>m!==a&&d.slice(-u).join("/")===o[a].slice(-u).join("/"));)u+=1;s.set(h,o[a].slice(-u).join("/")||"/")})}return new Map(i.map(({view:n,sources:r})=>{let o=r.every(d=>d.path===r[0].path),h=o?r[0].name:r.map(d=>d.name).join(" \u2194 "),a="";o?a=s.get(r[0].path)||"":r.some(d=>s.has(d.path))&&(a=r.map(d=>s.get(d.path)||t(d.path)).join(" \u2194 "));let u=r.some(d=>d.revision)?r.map(d=>d.revision||"working tree").join(" \u2194 "):n.kind==="diff"&&o?"diff":"";return[n.id,{name:h,description:[a,u].filter(Boolean).join(" \xB7 ")}]}))}function A(l){return typeof l=="string"?l:Array.isArray(l)?l.map(t=>t.text||t.refusal||`[${t.type}]`).join(`
3
- `):JSON.stringify(l,null,2)}function W(l){let t=[],e=new Map;for(let i of l){let s=i.payload,n=`record:${i.index}`;if(i.type==="compacted")t.push({key:n,kind:"compaction",label:"Compaction",body:s.message});else if(s.type==="function_call"||s.type==="custom_tool_call"){let r={key:`call:${s.call_id}`,kind:"tool",callId:s.call_id,toolName:s.name,label:[s.namespace,s.name].filter(Boolean).join("."),input:A(s.type==="custom_tool_call"?s.input:s.arguments)};e.set(s.call_id,r),t.push(r)}else if(s.type==="function_call_output"||s.type==="custom_tool_call_output"){let r=e.get(s.call_id);r||(r={key:`call:${s.call_id}`,kind:"tool",callId:s.call_id,toolName:s.name,label:s.name||"Tool"},e.set(s.call_id,r),t.push(r)),r.output=A(s.output)}else if(s.type==="message"||s.type==="agent_message")t.push({key:n,kind:s.role||"agent_message",label:s.type==="agent_message"?`${s.author} \u2192 ${s.recipient}`:s.role,phase:s.phase,body:A(s.content)});else if(s.type==="reasoning"){let r=[...s.summary||[],...s.content||[]].map(o=>o.text||"").filter(Boolean).join(`
2
+ function j(l){function t(n){let r=n.lastIndexOf("/");return r<0?".":n.slice(0,r)||"/"}let e=new Map,i=l.map(n=>{let o=(n.kind==="diff"?n.title.split(" <-> "):[n.title]).map(h=>{let a=/^(?:([0-9a-f]{40}|[0-9a-f]{64})|.+ \(([0-9a-f]{40}|[0-9a-f]{64})\)):(.+)$/i.exec(h),u=a?a[3]:h,d=u.slice(u.lastIndexOf("/")+1);return e.has(d)||e.set(d,new Set),e.get(d).add(u),{path:u,name:d,revision:a?(a[1]||a[2]).slice(0,7):null}});return{view:n,sources:o}}),s=new Map;for(let n of e.values()){if(n.size<2)continue;let r=Array.from(n),o=r.map(h=>t(h).split("/"));r.forEach((h,a)=>{let u=1;for(;u<o[a].length&&o.some((d,m)=>m!==a&&d.slice(-u).join("/")===o[a].slice(-u).join("/"));)u+=1;s.set(h,o[a].slice(-u).join("/")||"/")})}return new Map(i.map(({view:n,sources:r})=>{let o=r.every(d=>d.path===r[0].path),h=o?r[0].name:r.map(d=>d.name).join(" \u2194 "),a="";o?a=s.get(r[0].path)||"":r.some(d=>s.has(d.path))&&(a=r.map(d=>s.get(d.path)||t(d.path)).join(" \u2194 "));let u=r.some(d=>d.revision)?r.map(d=>d.revision||"working tree").join(" \u2194 "):n.kind==="diff"&&o?"diff":"";return[n.id,{name:h,description:[a,u].filter(Boolean).join(" \xB7 ")}]}))}function A(l){return typeof l=="string"?l:Array.isArray(l)?l.map(t=>t.text||t.refusal||`[${t.type}]`).join(`
3
+ `):JSON.stringify(l,null,2)}function H(l){let t=[],e=new Map;for(let i of l){let s=i.payload,n=`record:${i.index}`;if(i.type==="compacted")t.push({key:n,kind:"compaction",label:"Compaction",body:s.message});else if(s.type==="function_call"||s.type==="custom_tool_call"){let r={key:`call:${s.call_id}`,kind:"tool",callId:s.call_id,toolName:s.name,label:[s.namespace,s.name].filter(Boolean).join("."),input:A(s.type==="custom_tool_call"?s.input:s.arguments)};e.set(s.call_id,r),t.push(r)}else if(s.type==="function_call_output"||s.type==="custom_tool_call_output"){let r=e.get(s.call_id);r||(r={key:`call:${s.call_id}`,kind:"tool",callId:s.call_id,toolName:s.name,label:s.name||"Tool"},e.set(s.call_id,r),t.push(r)),r.output=A(s.output)}else if(s.type==="message"||s.type==="agent_message")t.push({key:n,kind:s.role||"agent_message",label:s.type==="agent_message"?`${s.author} \u2192 ${s.recipient}`:s.role,phase:s.phase,body:A(s.content)});else if(s.type==="reasoning"){let r=[...s.summary||[],...s.content||[]].map(o=>o.text||"").filter(Boolean).join(`
4
4
 
5
- `)||"No readable reasoning was recorded.";t.push({key:n,kind:"reasoning",label:"Reasoning",body:r})}else t.push({key:n,kind:"raw",label:s.type||i.type,body:A(s)})}return t}function K(l){let t={state:l.output===void 0?"pending":"completed"};if(l.toolName!=="exec"&&l.toolName!=="wait")return t;if(l.toolName==="wait"&&l.input!==void 0){let i;try{i=JSON.parse(l.input)}catch(s){if(!(s instanceof SyntaxError))throw s}typeof(i==null?void 0:i.cell_id)=="string"&&(t.cellId=i.cell_id)}let e=/^Script (running with cell ID (\S+)|completed|failed|terminated)\nWall time [\d.]+ seconds\nOutput:\n/.exec(l.output);return e&&(t.state=e[2]?"running":e[1],e[2]&&(t.cellId=e[2])),t}var T=class{constructor({viewport:t,request:e,renderMarkdown:i,sessionId:s,agentId:n,agentPath:r}){this.viewport=t,this.document=t.ownerDocument,this.window=this.document.defaultView,this.request=e,this.renderMarkdown=i,this.position=[0,0],this.sessionId=s,this.agentId=n,this.records=new Map,this.source=null,this.nextCursor=null,this.agentSessionId=null,this.active=!1,this.socket=null,this.requestController=null,this.reloadTimer=null,this.retryTimer=null,this.pendingRefresh=!1,this.pendingReset=!1,this.lastLoad=0,this.root=this.element("section","transcript"),this.root.dataset.sessionId=s;let o=this.element("div","snapshot-heading transcript-heading"),h=this.element("span","snapshot-label",r);h.title=`Agent: ${n}
6
- Session: ${s}`,this.status=this.element("span","snapshot-stamp","Loading\u2026"),this.refresh=this.element("button","content-mode-toggle","Refresh"),this.refresh.type="button",this.refresh.addEventListener("click",()=>this.load()),this.error=this.element("div","transcript-error"),this.error.setAttribute("role","alert"),this.error.hidden=!0,this.older=this.element("button","content-mode-toggle","Load earlier"),this.older.type="button",this.older.hidden=!0,this.older.addEventListener("click",()=>this.load(!0)),o.append(h,this.status,this.older,this.refresh),this.scroll=this.element("div","transcript-scroll"),this.scroll.tabIndex=0,this.scroll.setAttribute("aria-label",r+" transcript"),this.list=this.element("div","transcript-list","Loading transcript\u2026"),this.scroll.appendChild(this.list),this.root.append(o,this.error,this.scroll),this.visibilityChanged=()=>{this.document.hidden?this.disconnect():(this.load(),this.connect())}}element(t,e,i){let s=this.document.createElement(t);return s.className=e,i!==void 0&&(s.textContent=i),s}start(){this.active||(this.active=!0,[this.scroll.scrollLeft,this.scroll.scrollTop]=this.position,this.document.addEventListener("visibilitychange",this.visibilityChanged),this.document.hidden||(this.load(),this.connect()))}disconnect(){var e;clearTimeout(this.reloadTimer),clearTimeout(this.retryTimer),this.reloadTimer=this.retryTimer=null,(e=this.requestController)==null||e.abort(),this.requestController=null;let t=this.socket;this.socket=null,t&&t.close()}stop(){this.active=!1,this.document.removeEventListener("visibilitychange",this.visibilityChanged),this.disconnect(),this.position=[this.scroll.scrollLeft,this.scroll.scrollTop]}schedule(t=!1){this.pendingReset||(this.pendingReset=t),!(this.reloadTimer!==null||!this.active||this.document.hidden)&&(this.reloadTimer=setTimeout(()=>{this.reloadTimer=null,this.load()},Math.max(150,1e3-(Date.now()-this.lastLoad))))}connect(){if(this.socket||!this.active||this.document.hidden)return;let t=new URL("ws/session",this.window.location.href);t.protocol=t.protocol==="https:"?"wss:":"ws:",t.searchParams.set("session_id",this.sessionId),t.searchParams.set("agent_id",this.agentId);let e=new this.window.WebSocket(t);this.socket=e,e.onmessage=i=>{if(this.socket!==e)return;let s=JSON.parse(i.data);if(s.type==="error"){this.showError(s.error);return}let n=s.state;n&&(this.agentSessionId!==null&&this.agentSessionId!==n.agent_session_id&&(this.pendingReset=!0),this.agentSessionId=n.agent_session_id,this.status.textContent=n.running?"Running":"Live"),(s.type==="hello"||["model_called","model_completed","tool_started","tool_completed","turn_completed","turn_failed","turn_interrupted","session_state","compact_completed","auto_compact_completed"].includes(s.kind))&&this.schedule(s.kind==="compact_completed"||s.kind==="auto_compact_completed")},e.onclose=i=>{this.socket===e&&(this.socket=null,this.status.textContent="Disconnected",i.code!==1e3&&i.code!==1008&&(this.retryTimer=setTimeout(()=>{this.retryTimer=null,this.connect()},2e3)))}}showError(t){this.error.textContent=t,this.error.hidden=!t}async load(t=!1){if(!this.active||this.document.hidden||t&&!this.nextCursor)return;if(this.requestController){t||(this.pendingRefresh=!0);return}this.pendingReset&&(t=!1);let e=new AbortController;this.requestController=e;let i=this.pendingReset;this.pendingReset=!1,this.pendingRefresh=!1,this.older.disabled=!0;let s=n=>{let r=new URLSearchParams({agent_id:this.agentId,limit:"100"});return n!==null&&r.set("before",n),this.request(`api/sessions/${encodeURIComponent(this.sessionId)}/history?${r}`,{signal:e.signal})};try{let n=await s(t?this.nextCursor:null),r=n.items,o=Array.from(this.records.values()),h=o.length?o[o.length-1].index:-1,a=n.next_cursor;if(!t&&!i&&this.source===n.source&&o.length)for(;r.length&&r[0].index>h&&a!==null;){let m=await s(a);if(m.source!==n.source)throw Object.assign(new Error("History changed"),{status:409});r=m.items.concat(r),a=m.next_cursor}if(this.requestController!==e)return;let u=r.filter(m=>this.records.has(m.index)),d=i||this.source!==n.source||!t&&o.length&&(!u.length||u.some(m=>JSON.stringify(m)!==JSON.stringify(this.records.get(m.index))));d&&(this.records.clear(),r=n.items);for(let m of r)this.records.set(m.index,m);this.records=new Map(Array.from(this.records).sort((m,S)=>m[0]-S[0])),(t||d||!o.length)&&(this.nextCursor=n.next_cursor),this.source=n.source,this.showError(""),this.render()}catch(n){if(this.requestController!==e||n.name==="AbortError")return;n.status===409?(this.pendingReset=!0,this.pendingRefresh=!0):(this.showError("Unable to load transcript: "+n.message),[401,403,404].includes(n.status)&&this.disconnect())}finally{this.requestController===e&&(this.requestController=null,this.lastLoad=Date.now(),this.older.disabled=!1,(this.pendingRefresh||this.pendingReset)&&this.schedule())}}renderBlock(t){let e=t.kind==="tool",i=this.element("details","transcript-record");i.dataset.key=t.key,i.dataset.kind=t.kind,t.toolName&&(i.dataset.tool=t.toolName),i.open=t.kind!=="reasoning"&&t.kind!=="compaction";let s=this.element("summary","transcript-marker"),n=this.element("span","transcript-marker-line"),r=this.element("span","transcript-label");if(r.appendChild(this.element("span","transcript-role",t.label)),n.appendChild(r),s.appendChild(n),e){s.title="Call: "+t.callId;let o=K(t);if(o.cellId){let a=this.element("span","transcript-cell",o.cellId);a.title="Cell: "+o.cellId;let u=0;for(let d of o.cellId)u=(u*31+d.charCodeAt(0))%80;a.style.setProperty("--transcript-cell-hue",200+u),r.appendChild(a)}let h=this.element("span","transcript-phase",{pending:"Awaiting result",running:"Running",completed:"Completed",failed:"Failed",terminated:"Terminated"}[o.state]);if(h.dataset.state=o.state,n.appendChild(h),i.append(s,t.input===void 0?this.element("p","transcript-note","Load earlier records to see this call's input."):this.element("pre","transcript-code",t.input)),t.output!==void 0){let a=this.element("details","transcript-output");a.append(this.element("summary","","Output"),this.element("pre","transcript-code",t.output)),i.appendChild(a)}}else{t.phase&&n.appendChild(this.element("span","transcript-phase",t.phase));let o=this.element("div","transcript-body markdown");t.kind!=="raw"&&this.renderMarkdown?this.renderMarkdown(o,t.body||""):o.appendChild(this.element("pre","transcript-code",t.body)),i.append(s,o)}return i.signature=JSON.stringify(t),i}render(){let t=this.scroll.scrollHeight-this.scroll.scrollTop-this.scroll.clientHeight<40,e=this.scroll.getBoundingClientRect().top,i=Array.from(this.list.children).find(a=>a.getBoundingClientRect().bottom>e),s=i==null?void 0:i.getBoundingClientRect().top,n=new Map(Array.from(this.list.children,a=>[a.dataset.key,a])),r=W(Array.from(this.records.values())),o=r.map(a=>{let u=JSON.stringify(a),d=n.get(a.key);if((d==null?void 0:d.signature)===u)return d;let m=this.renderBlock(a);if(d){m.open=d.open;let S=d.querySelector(".transcript-output"),R=m.querySelector(".transcript-output");S&&R&&(R.open=S.open)}return m});this.list.children.length||(this.list.textContent="");let h=new Set(o);for(let a of Array.from(this.list.children))h.has(a)||a.remove();if(o.forEach((a,u)=>{this.list.children[u]!==a&&this.list.insertBefore(a,this.list.children[u]||null)}),r.length||(this.list.textContent="No messages yet."),this.older.hidden=this.nextCursor===null,t)this.scroll.scrollTop=this.scroll.scrollHeight;else if(i){let a=o.find(u=>u.dataset.key===i.dataset.key);a&&(this.scroll.scrollTop+=a.getBoundingClientRect().top-s)}}};var E=class l{constructor(t,e,i,s,n,r=null){this.element=t,this.changed=e,this.submit=i,this.editContext=s,this.error=n,this.recallInput=r,this.recalledParts=null,this.composing=!1,this.selection={start:0,end:0},this.undo=[],this.redo=[],this.previous=this.read(),t.addEventListener("input",o=>{o.isComposing||this.record(),this.changed()}),t.addEventListener("compositionstart",()=>{this.composing=!0}),t.addEventListener("compositionend",()=>{this.composing=!1,this.record(),this.changed()}),document.addEventListener("selectionchange",()=>{this.captureSelection()&&this.changed()}),t.addEventListener("keydown",o=>this.keydown(o)),t.addEventListener("beforeinput",o=>{o.inputType==="historyUndo"||o.inputType==="historyRedo"?(o.preventDefault(),this.history(o.inputType==="historyUndo")):o.inputType.startsWith("format")&&o.preventDefault()}),t.addEventListener("click",o=>{let h=o.target.closest(".context-token");h&&this.editContext(JSON.parse(h.dataset.context))}),t.addEventListener("mousedown",o=>{o.target.closest(".context-token")&&o.preventDefault()}),t.addEventListener("copy",o=>this.copy(o,!1)),t.addEventListener("cut",o=>this.copy(o,!0)),t.addEventListener("paste",o=>{o.preventDefault(),this.paste(o.clipboardData)}),t.addEventListener("dragover",o=>o.preventDefault()),t.addEventListener("drop",o=>{o.preventDefault();let h=document.caretRangeFromPoint(o.clientX,o.clientY);if(h&&t.contains(h.startContainer)){let a=window.getSelection();a.removeAllRanges(),a.addRange(h),this.captureSelection()}this.paste(o.dataTransfer)})}static size(t){return t.reduce((e,i)=>e+(i.type==="context"?1:i.text.length),0)}static text(t){return t.map(e=>e.text).join("")}static slice(t,e,i){let s=[],n=0;for(let r of t){let o=l.size([r]);e<n+o&&i>n&&s.push(r.type==="context"?{...r}:{type:"text",text:r.text.slice(Math.max(0,e-n),i-n)}),n+=o}return s}parts(t=this.element){let e=[],i=n=>{if(!n)return;let r=e.at(-1);(r==null?void 0:r.type)==="text"?r.text+=n:e.push({type:"text",text:n})},s=n=>{var r;for(let o of n.childNodes)o.nodeType===Node.TEXT_NODE?i(o.data):(r=o.dataset)!=null&&r.context?e.push(JSON.parse(o.dataset.context)):o.nodeName==="BR"?!o.hasAttribute("data-tail")&&n.childNodes.length>1&&i(`
5
+ `)||"No readable reasoning was recorded.";t.push({key:n,kind:"reasoning",label:"Reasoning",body:r})}else t.push({key:n,kind:"raw",label:s.type||i.type,body:A(s)})}return t}function W(l){let t={state:l.output===void 0?"pending":"completed"};if(l.toolName!=="exec"&&l.toolName!=="wait")return t;if(l.toolName==="wait"&&l.input!==void 0){let i;try{i=JSON.parse(l.input)}catch(s){if(!(s instanceof SyntaxError))throw s}typeof(i==null?void 0:i.cell_id)=="string"&&(t.cellId=i.cell_id)}let e=/^Script (running with cell ID (\S+)|completed|failed|terminated)\nWall time [\d.]+ seconds\nOutput:\n/.exec(l.output);return e&&(t.state=e[2]?"running":e[1],e[2]&&(t.cellId=e[2])),t}var T=class{constructor({viewport:t,request:e,renderMarkdown:i,sessionId:s,agentId:n,agentPath:r}){this.viewport=t,this.document=t.ownerDocument,this.window=this.document.defaultView,this.request=e,this.renderMarkdown=i,this.position=[0,0],this.sessionId=s,this.agentId=n,this.records=new Map,this.source=null,this.nextCursor=null,this.agentSessionId=null,this.active=!1,this.socket=null,this.requestController=null,this.reloadTimer=null,this.retryTimer=null,this.pendingRefresh=!1,this.pendingReset=!1,this.lastLoad=0,this.root=this.element("section","transcript"),this.root.dataset.sessionId=s;let o=this.element("div","snapshot-heading transcript-heading"),h=this.element("span","snapshot-label",r);h.title=`Agent: ${n}
6
+ Session: ${s}`,this.status=this.element("span","snapshot-stamp","Loading\u2026"),this.refresh=this.element("button","content-mode-toggle","Refresh"),this.refresh.type="button",this.refresh.addEventListener("click",()=>this.load()),this.error=this.element("div","transcript-error"),this.error.setAttribute("role","alert"),this.error.hidden=!0,this.older=this.element("button","content-mode-toggle","Load earlier"),this.older.type="button",this.older.hidden=!0,this.older.addEventListener("click",()=>this.load(!0)),o.append(h,this.status,this.older,this.refresh),this.scroll=this.element("div","transcript-scroll"),this.scroll.tabIndex=0,this.scroll.setAttribute("aria-label",r+" transcript"),this.list=this.element("div","transcript-list","Loading transcript\u2026"),this.scroll.appendChild(this.list),this.root.append(o,this.error,this.scroll),this.visibilityChanged=()=>{this.document.hidden?this.disconnect():(this.load(),this.connect())}}element(t,e,i){let s=this.document.createElement(t);return s.className=e,i!==void 0&&(s.textContent=i),s}start(){this.active||(this.active=!0,[this.scroll.scrollLeft,this.scroll.scrollTop]=this.position,this.document.addEventListener("visibilitychange",this.visibilityChanged),this.document.hidden||(this.load(),this.connect()))}disconnect(){var e;clearTimeout(this.reloadTimer),clearTimeout(this.retryTimer),this.reloadTimer=this.retryTimer=null,(e=this.requestController)==null||e.abort(),this.requestController=null;let t=this.socket;this.socket=null,t&&t.close()}stop(){this.active=!1,this.document.removeEventListener("visibilitychange",this.visibilityChanged),this.disconnect(),this.position=[this.scroll.scrollLeft,this.scroll.scrollTop]}schedule(t=!1){this.pendingReset||(this.pendingReset=t),!(this.reloadTimer!==null||!this.active||this.document.hidden)&&(this.reloadTimer=setTimeout(()=>{this.reloadTimer=null,this.load()},Math.max(150,1e3-(Date.now()-this.lastLoad))))}connect(){if(this.socket||!this.active||this.document.hidden)return;let t=new URL("ws/session",this.window.location.href);t.protocol=t.protocol==="https:"?"wss:":"ws:",t.searchParams.set("session_id",this.sessionId),t.searchParams.set("agent_id",this.agentId);let e=new this.window.WebSocket(t);this.socket=e,e.onmessage=i=>{if(this.socket!==e)return;let s=JSON.parse(i.data);if(s.type==="error"){this.showError(s.error);return}let n=s.state;n&&(this.agentSessionId!==null&&this.agentSessionId!==n.agent_session_id&&(this.pendingReset=!0),this.agentSessionId=n.agent_session_id,this.status.textContent=n.running?"Running":"Live"),(s.type==="hello"||["model_called","model_completed","tool_started","tool_completed","turn_completed","turn_failed","turn_interrupted","session_state","compact_completed","auto_compact_completed"].includes(s.kind))&&this.schedule(s.kind==="compact_completed"||s.kind==="auto_compact_completed")},e.onclose=i=>{this.socket===e&&(this.socket=null,this.status.textContent="Disconnected",i.code!==1e3&&i.code!==1008&&(this.retryTimer=setTimeout(()=>{this.retryTimer=null,this.connect()},2e3)))}}showError(t){this.error.textContent=t,this.error.hidden=!t}async load(t=!1){if(!this.active||this.document.hidden||t&&!this.nextCursor)return;if(this.requestController){t||(this.pendingRefresh=!0);return}this.pendingReset&&(t=!1);let e=new AbortController;this.requestController=e;let i=this.pendingReset;this.pendingReset=!1,this.pendingRefresh=!1,this.older.disabled=!0;let s=n=>{let r=new URLSearchParams({agent_id:this.agentId,limit:"100"});return n!==null&&r.set("before",n),this.request(`api/sessions/${encodeURIComponent(this.sessionId)}/history?${r}`,{signal:e.signal})};try{let n=await s(t?this.nextCursor:null),r=n.items,o=Array.from(this.records.values()),h=o.length?o[o.length-1].index:-1,a=n.next_cursor;if(!t&&!i&&this.source===n.source&&o.length)for(;r.length&&r[0].index>h&&a!==null;){let m=await s(a);if(m.source!==n.source)throw Object.assign(new Error("History changed"),{status:409});r=m.items.concat(r),a=m.next_cursor}if(this.requestController!==e)return;let u=r.filter(m=>this.records.has(m.index)),d=i||this.source!==n.source||!t&&o.length&&(!u.length||u.some(m=>JSON.stringify(m)!==JSON.stringify(this.records.get(m.index))));d&&(this.records.clear(),r=n.items);for(let m of r)this.records.set(m.index,m);this.records=new Map(Array.from(this.records).sort((m,S)=>m[0]-S[0])),(t||d||!o.length)&&(this.nextCursor=n.next_cursor),this.source=n.source,this.showError(""),this.render()}catch(n){if(this.requestController!==e||n.name==="AbortError")return;n.status===409?(this.pendingReset=!0,this.pendingRefresh=!0):(this.showError("Unable to load transcript: "+n.message),[401,403,404].includes(n.status)&&this.disconnect())}finally{this.requestController===e&&(this.requestController=null,this.lastLoad=Date.now(),this.older.disabled=!1,(this.pendingRefresh||this.pendingReset)&&this.schedule())}}renderBlock(t){let e=t.kind==="tool",i=this.element("details","transcript-record");i.dataset.key=t.key,i.dataset.kind=t.kind,t.toolName&&(i.dataset.tool=t.toolName),i.open=t.kind!=="reasoning"&&t.kind!=="compaction";let s=this.element("summary","transcript-marker"),n=this.element("span","transcript-marker-line"),r=this.element("span","transcript-label");if(r.appendChild(this.element("span","transcript-role",t.label)),n.appendChild(r),s.appendChild(n),e){s.title="Call: "+t.callId;let o=W(t);if(o.cellId){let a=this.element("span","transcript-cell",o.cellId);a.title="Cell: "+o.cellId;let u=0;for(let d of o.cellId)u=(u*31+d.charCodeAt(0))%80;a.style.setProperty("--transcript-cell-hue",200+u),r.appendChild(a)}let h=this.element("span","transcript-phase",{pending:"Awaiting result",running:"Running",completed:"Completed",failed:"Failed",terminated:"Terminated"}[o.state]);if(h.dataset.state=o.state,n.appendChild(h),i.append(s,t.input===void 0?this.element("p","transcript-note","Load earlier records to see this call's input."):this.element("pre","transcript-code",t.input)),t.output!==void 0){let a=this.element("details","transcript-output");a.append(this.element("summary","","Output"),this.element("pre","transcript-code",t.output)),i.appendChild(a)}}else{t.phase&&n.appendChild(this.element("span","transcript-phase",t.phase));let o=this.element("div","transcript-body markdown");t.kind!=="raw"&&this.renderMarkdown?this.renderMarkdown(o,t.body||""):o.appendChild(this.element("pre","transcript-code",t.body)),i.append(s,o)}return i.signature=JSON.stringify(t),i}render(){let t=this.scroll.scrollHeight-this.scroll.scrollTop-this.scroll.clientHeight<40,e=this.scroll.getBoundingClientRect().top,i=Array.from(this.list.children).find(a=>a.getBoundingClientRect().bottom>e),s=i==null?void 0:i.getBoundingClientRect().top,n=new Map(Array.from(this.list.children,a=>[a.dataset.key,a])),r=H(Array.from(this.records.values())),o=r.map(a=>{let u=JSON.stringify(a),d=n.get(a.key);if((d==null?void 0:d.signature)===u)return d;let m=this.renderBlock(a);if(d){m.open=d.open;let S=d.querySelector(".transcript-output"),R=m.querySelector(".transcript-output");S&&R&&(R.open=S.open)}return m});this.list.children.length||(this.list.textContent="");let h=new Set(o);for(let a of Array.from(this.list.children))h.has(a)||a.remove();if(o.forEach((a,u)=>{this.list.children[u]!==a&&this.list.insertBefore(a,this.list.children[u]||null)}),r.length||(this.list.textContent="No messages yet."),this.older.hidden=this.nextCursor===null,t)this.scroll.scrollTop=this.scroll.scrollHeight;else if(i){let a=o.find(u=>u.dataset.key===i.dataset.key);a&&(this.scroll.scrollTop+=a.getBoundingClientRect().top-s)}}};var E=class l{constructor(t,e,i,s,n,r=null){this.element=t,this.changed=e,this.submit=i,this.editContext=s,this.error=n,this.recallInput=r,this.recalledParts=null,this.composing=!1,this.selection={start:0,end:0},this.undo=[],this.redo=[],this.previous=this.read(),t.addEventListener("input",o=>{o.isComposing||this.record(),this.changed()}),t.addEventListener("compositionstart",()=>{this.composing=!0}),t.addEventListener("compositionend",()=>{this.composing=!1,this.record(),this.changed()}),document.addEventListener("selectionchange",()=>{this.captureSelection()&&this.changed()}),t.addEventListener("keydown",o=>this.keydown(o)),t.addEventListener("beforeinput",o=>{o.inputType==="historyUndo"||o.inputType==="historyRedo"?(o.preventDefault(),this.history(o.inputType==="historyUndo")):o.inputType.startsWith("format")&&o.preventDefault()}),t.addEventListener("click",o=>{let h=o.target.closest(".context-token");h&&this.editContext(JSON.parse(h.dataset.context))}),t.addEventListener("mousedown",o=>{o.target.closest(".context-token")&&o.preventDefault()}),t.addEventListener("copy",o=>this.copy(o,!1)),t.addEventListener("cut",o=>this.copy(o,!0)),t.addEventListener("paste",o=>{o.preventDefault(),this.paste(o.clipboardData)}),t.addEventListener("dragover",o=>o.preventDefault()),t.addEventListener("drop",o=>{o.preventDefault();let h=document.caretRangeFromPoint(o.clientX,o.clientY);if(h&&t.contains(h.startContainer)){let a=window.getSelection();a.removeAllRanges(),a.addRange(h),this.captureSelection()}this.paste(o.dataTransfer)})}static size(t){return t.reduce((e,i)=>e+(i.type==="context"?1:i.text.length),0)}static text(t){return t.map(e=>e.text).join("")}static slice(t,e,i){let s=[],n=0;for(let r of t){let o=l.size([r]);e<n+o&&i>n&&s.push(r.type==="context"?{...r}:{type:"text",text:r.text.slice(Math.max(0,e-n),i-n)}),n+=o}return s}parts(t=this.element){let e=[],i=n=>{if(!n)return;let r=e.at(-1);(r==null?void 0:r.type)==="text"?r.text+=n:e.push({type:"text",text:n})},s=n=>{var r;for(let o of n.childNodes)o.nodeType===Node.TEXT_NODE?i(o.data):(r=o.dataset)!=null&&r.context?e.push(JSON.parse(o.dataset.context)):o.nodeName==="BR"?!o.hasAttribute("data-tail")&&n.childNodes.length>1&&i(`
7
7
  `):(["DIV","P"].includes(o.nodeName)&&e.length&&!e.at(-1).text.endsWith(`
8
8
  `)&&i(`
9
9
  `),s(o))};return s(t),e}captureSelection(){if(document.activeElement!==this.element)return!1;let t=window.getSelection();if(!t.rangeCount)return!1;let e=t.getRangeAt(0);if(!this.element.contains(e.startContainer)||!this.element.contains(e.endContainer))return!1;let i=document.createRange();i.selectNodeContents(this.element),i.setEnd(e.startContainer,e.startOffset);let s=l.size(this.parts(i.cloneContents()));return this.selection={start:s,end:s+l.size(this.parts(e.cloneContents()))},!0}read(){return this.captureSelection(),{parts:this.parts(),selection:{...this.selection}}}set(t){this.recalledParts=null,this.undo=[],this.redo=[],this.render(t),document.activeElement===this.element&&this.focus(),this.previous=this.read()}render(t){let e=t.parts||[];this.element.replaceChildren();for(let s of e)if(s.type==="text")this.element.append(document.createTextNode(s.text));else{let n=document.createElement("span");n.className="context-token",n.contentEditable="false",n.dataset.context=JSON.stringify(s),n.textContent=s.label,n.title=s.label+`
10
10
  Click to edit context; Backspace / Delete to remove`,this.element.append(n,document.createTextNode(""))}if(!e.length||e.at(-1).type==="text"&&e.at(-1).text.endsWith(`
11
11
  `)){let s=document.createElement("br");s.dataset.tail="",this.element.append(s)}let i=l.size(e);this.selection=t.selection||{start:i,end:i},this.selection={start:Math.min(this.selection.start,i),end:Math.min(this.selection.end,i)},this.element.classList.toggle("empty",!e.length)}focus(){this.element.focus({preventScroll:!0});let t=s=>{let n=r=>{var o;for(let h=0;h<r.childNodes.length;h++){let a=r.childNodes[h];if(a.nodeType===Node.TEXT_NODE){if(s<=a.length)return[a,s];s-=a.length}else if((o=a.dataset)!=null&&o.context){if(s===0)return[r,h];if(s-=1,s===0)return[r,h+1]}else if(a.nodeName==="BR"){if(s===0)return[r,h];a.hasAttribute("data-tail")||(s-=1)}else{let u=n(a);if(u)return u}}};return n(this.element)||[this.element,this.element.childNodes.length]},e=document.createRange();e.setStart(...t(this.selection.start)),e.setEnd(...t(this.selection.end));let i=window.getSelection();i.removeAllRanges(),i.addRange(e)}record(){let t=this.read();JSON.stringify(t.parts)!==JSON.stringify(this.previous.parts)&&(this.undo.push(this.previous),this.undo.length>40&&this.undo.shift(),this.redo=[],this.previous=t),this.element.classList.toggle("empty",!t.parts.length)}replace(t,e,i){let s=this.read(),n=[...l.slice(s.parts,0,t),...i,...l.slice(s.parts,e,l.size(s.parts))],r=t+l.size(i);this.render({parts:n,selection:{start:r,end:r}}),this.focus(),this.record(),this.changed()}insert(t){this.captureSelection(),this.replace(this.selection.start,this.selection.end,t.map(e=>({...e,type:"context",id:crypto.getRandomValues(new Uint32Array(4)).join("-")})))}updateContext(t,e){for(let i of this.element.querySelectorAll(".context-token")){let s=JSON.parse(i.dataset.context);s.id===t&&(i.dataset.context=JSON.stringify({...s,text:e}))}this.record(),this.changed()}removeContext(t){let e=0;for(let i of this.parts()){if(i.type==="context"&&i.id===t){this.replace(e,e+1,[]);return}e+=l.size([i])}}history(t){let e=t?this.undo:this.redo;e.length&&((t?this.redo:this.undo).push(this.read()),this.render(e.pop()),this.focus(),this.previous=this.read(),this.changed())}keydown(t){var i;if(t.isComposing||this.composing||t.keyCode===229)return;let e=t.ctrlKey||t.metaKey;if(this.recallInput&&["ArrowUp","ArrowDown"].includes(t.key)&&!e&&!t.altKey&&!t.shiftKey){let s=this.read();if(s.selection.start===s.selection.end){let n=s.selection.start,r=l.text(s.parts),o=t.key==="ArrowUp",h=l.text(l.slice(s.parts,0,n)),a=l.text(l.slice(s.parts,n,l.size(s.parts)));if(this.recalledParts===JSON.stringify(s.parts)||!r||!(o?h:a).includes(`
12
12
  `)){let d=this.recallInput(o,s);d&&(t.preventDefault(),this.render(d),this.recalledParts=JSON.stringify(d.parts),this.focus(),this.record(),this.changed())}}}else if(e&&(t.key.toLowerCase()==="z"||t.key.toLowerCase()==="y"))t.preventDefault(),this.history(t.key.toLowerCase()==="z"&&!t.shiftKey);else if(t.key==="Enter")t.preventDefault(),t.shiftKey?(this.captureSelection(),this.replace(this.selection.start,this.selection.end,[{type:"text",text:`
13
- `}])):this.submit();else if(["Backspace","Delete"].includes(t.key)&&!e&&!t.altKey){this.captureSelection();let{start:s,end:n}=this.selection,r=t.key==="Backspace"?s-1:s;s===n&&((i=l.slice(this.parts(),r,r+1)[0])==null?void 0:i.type)==="context"&&(t.preventDefault(),this.replace(r,r+1,[]))}}copy(t,e){if(!this.captureSelection()||this.selection.start===this.selection.end)return;let i=l.slice(this.parts(),this.selection.start,this.selection.end);t.clipboardData.setData("text/plain",l.text(i)),t.clipboardData.setData("application/x-pycodex-parts",JSON.stringify(i)),t.preventDefault(),e&&this.replace(this.selection.start,this.selection.end,[])}paste(t){try{let e=t.getData("application/x-pycodex-parts"),i=e?JSON.parse(e):[{type:"text",text:t.getData("text/plain")}];if(!Array.isArray(i)||i.some(s=>!s||typeof s.text!="string"||!["text","context"].includes(s.type)||s.type==="context"&&typeof s.label!="string"))throw new Error("Invalid context format in clipboard.");this.captureSelection(),this.replace(this.selection.start,this.selection.end,i.map(s=>s.type==="context"?{...s,id:crypto.getRandomValues(new Uint32Array(4)).join("-")}:s))}catch(e){this.error(e.message)}}};function X(l){let t=l.trim().match(/^<(clock_tick|exec_command_completed)>\s*([\s\S]*?)\s*<\/\1>$/);if(!t)return!1;try{let e=JSON.parse(t[2]);return e!==null&&typeof e=="object"&&!Array.isArray(e)}catch(e){return!1}}var D=class{constructor(){this.entries=[],this.seen=new Set,this.pending=[],this.index=null,this.draft=null}remember(t){let e=t.parts.map(i=>({...i}));E.text(e).trim()&&(this.append({parts:e}),this.pending.push(E.text(e).trim()),this.pending.length>100&&this.pending.shift(),this.reset())}append(t){this.entries.push(t),this.entries.length>100&&(this.entries.shift(),this.index!==null&&(this.index=Math.max(0,this.index-1)))}update(t){for(let e of t||[]){let i=e.submission_id||e.turn_id;if(!i||this.seen.has(i))continue;this.seen.add(i);let s=e.prompt;if(!s||!s.trim())continue;let n=this.pending.indexOf(s.trim());if(n!==-1){this.pending.splice(n,1);continue}e.kind==="compaction"||X(s)||!["web","cli","feishu","resume","user"].includes(e.sender)||this.append({parts:[{type:"text",text:s}]})}}reset(){this.index=null,this.draft=null}recall(t,e){if(this.index!==null&&JSON.stringify(e.parts)!==JSON.stringify(this.entries[this.index].parts)&&this.reset(),t){if(!this.entries.length||this.index===0)return null;this.index===null&&(this.draft=e,this.index=this.entries.length),this.index-=1}else{if(this.index===null)return null;if(this.index+=1,this.index>=this.entries.length){let i=this.draft;return this.reset(),i}}return{parts:this.entries[this.index].parts.map(i=>({...i}))}}};function it(l,t=!0){if(typeof l!="string"||!l||l!==l.trim()||/[\x00-\x1f\x7f]/.test(l))return!1;if(/^(?:diff:|git:|workspace:\/\/canvas\/?$)/i.test(l))return!0;if(!t||/^(?:https?|ftps?|mailto|tel|sms|javascript|vbscript|data|blob|about|file):/i.test(l))return!1;let e=l.split("#");if(e.length>2||e.length===2&&!/^L-?\d+$/i.test(e[1]))return!1;let i=e[0].replace(/:-?\d+$/,"");return!!i&&!i.startsWith("//")&&!i.includes("?")&&(!/^[a-z][a-z\d+.-]*:/i.test(i)||/^[a-z]:(?:[/\\]|%2f|%5c)/i.test(i))}var P=class{constructor({request:t,onChange:e,onSelect:i,selected:s=null,enableBoard:n=!0}){this.request=t,this.onChange=e,this.onSelect=i,this.enableBoard=n,this.views=[],this.transcripts=new Map,this.activeId=n?"board":null,this.snapshot=null,this.selection=null,this.displayMode=null,this.loading=!1,this.error="",this.closing=new Set,this.cache=new Map,this.initialSelection=s,this.initialized=!1,this.mutation=0,this.pollRequest=null,this.contentRequest=null,this.openRequest=null,this.timer=null}start(){this.timer===null&&(this.poll(),this.timer=setInterval(()=>this.poll(),2e3))}stop(){clearInterval(this.timer),this.timer=null,this.cancelOpen(),this.pollRequest&&this.pollRequest.abort(),this.contentRequest&&this.contentRequest.abort(),this.pollRequest=null,this.contentRequest=null,this.loading=!1}async poll(){if(this.pollRequest||this.openRequest)return;let t=new AbortController,e=this.mutation;this.pollRequest=t;try{let i=await this.request("api/views",{signal:t.signal});if(this.pollRequest!==t||e!==this.mutation)return;this.updateViews(i.views);let s=new Set(this.views.map(r=>r.id));this.error="";let n=this.activeId;this.initialized||(n=this.initialSelection||this.defaultId(),this.initialized=!0),(n==="board"&&!this.enableBoard||n!==null&&n!=="board"&&!s.has(n))&&(n=this.defaultId()),n!==this.activeId||n!==null&&n!=="board"&&!this.snapshot&&!this.loading?this.select(n):(n!==null&&n!=="board"&&!this.cache.has(n)&&!this.contentRequest&&this.load(n),this.onChange(this))}catch(i){this.pollRequest===t&&e===this.mutation&&i.name!=="AbortError"&&(this.error="Unable to load tabs: "+i.message,this.onChange(this))}finally{this.pollRequest===t&&(this.pollRequest=null)}}defaultId(){return this.enableBoard?"board":this.views.length?this.views[0].id:null}updateViews(t){this.views=t.concat(Array.from(this.transcripts.values()));let e=new Map(this.views.map(i=>[i.id,i.revision]));for(let[i,s]of this.cache)(!e.has(i)||s.revision<e.get(i))&&this.cache.delete(i)}cancelOpen(){this.openRequest&&this.openRequest.abort(),this.openRequest=null}openTranscript(t,e,i){let s=`transcript:${t}:${e}`;if(!this.transcripts.has(s)){let n={id:s,kind:"transcript",title:i,sessionId:t,agentId:e,revision:1,documents:[]};this.transcripts.set(s,n),this.views.push(n),this.cache.set(s,n)}return this.initialized=!0,this.select(s)}async open(t,e,i){if(this.cancelOpen(),/^workspace:\/\/canvas\/?$/i.test(t)){if(!this.enableBoard)throw new Error("Canvas is disabled for this workspace.");await this.select("board");return}let s=new AbortController;this.openRequest=s,this.mutation+=1,this.error="",this.onChange(this);try{let n=await this.request("api/views/open",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({href:t,src_path:e,session_id:i}),signal:s.signal});if(this.openRequest!==s)return;this.mutation+=1,this.updateViews(n.views);let r=n.view;return this.cache.set(r.id,r),this.initialized=!0,this.openRequest=null,this.select(r.id,r.selection?{...r.selection,revision:r.reveal_revision,contentRevision:r.revision}:null,r.selection?"source":"preview")}catch(n){if(this.openRequest!==s||n.name==="AbortError")return;throw this.error="Unable to open view: "+n.message,n}finally{this.openRequest===s&&(this.openRequest=null,this.onChange(this))}}async select(t,e=null,i=null){if(t==="board"&&!this.enableBoard||t!==null&&t!=="board"&&!this.views.some(n=>n.id===t))return;this.cancelOpen();let s=t===this.activeId?this.snapshot:null;this.contentRequest&&this.contentRequest.abort(),this.contentRequest=null,this.activeId=t,this.selection=e,this.displayMode=i,this.initialized||(this.initialSelection=t),this.snapshot=this.cache.get(t)||s,this.loading=t!==null&&t!=="board"&&!this.snapshot,this.error="",this.onSelect(t),this.onChange(this),!(t===null||t==="board"||this.cache.has(t))&&await this.load(t)}setDisplayMode(t){!this.snapshot||this.activeId===null||this.activeId==="board"||!["source","preview"].includes(t)||(this.cancelOpen(),this.selection=null,this.displayMode=t,this.onChange(this))}async load(t){let e=new AbortController;this.contentRequest=e;try{let i=await this.request("api/views/"+encodeURIComponent(t),{signal:e.signal});if(this.contentRequest!==e||this.activeId!==t)return;let s=this.views.find(n=>n.id===t);if(!s||i.revision<s.revision)return;this.cache.set(t,i),this.snapshot=i,this.error=""}catch(i){if(this.contentRequest!==e||this.activeId!==t||i.name==="AbortError")return;this.error="Unable to load view: "+i.message}finally{this.contentRequest===e&&(this.contentRequest=null,this.loading=!1,this.onChange(this))}}async close(t){if(!(t===null||t==="board"||this.closing.has(t))){this.cancelOpen(),this.closing.add(t),this.mutation+=1,this.onChange(this);try{this.transcripts.has(t)?this.transcripts.delete(t):await this.request("api/views/"+encodeURIComponent(t),{method:"DELETE"}),this.mutation+=1;let e=this.views.findIndex(i=>i.id===t);this.views=this.views.filter(i=>i.id!==t),this.cache.delete(t),this.activeId===t&&await this.select(e>0?this.views[e-1].id:this.defaultId())}catch(e){this.error="Unable to close tab: "+e.message}finally{this.closing.delete(t),this.onChange(this)}}}};function g(l,t,e,i){let s=l.createElement(t);return s.className=e,i!==void 0&&(s.textContent=i),s}var B=class{constructor(t,e=[0,0]){this.document=t.ownerDocument,this.window=this.document.defaultView,this.position=e,this.generation=0,this.frame=g(this.document,"iframe","snapshot-html"),this.frame.title="HTML preview",this.receive=i=>{if(i.source!==this.frame.contentWindow)return;let s=i.data;!s||s.generation!==this.generation||(s.type==="workspace-preview-ready"?this.frame.contentWindow.postMessage({type:"workspace-preview-restore",generation:this.generation,position:this.position},"*"):s.type==="workspace-preview-scroll"&&Array.isArray(s.position)&&s.position.length===2&&s.position.every(Number.isFinite)&&(this.position=s.position))},this.window.addEventListener("message",this.receive),t.appendChild(this.frame)}update(t){if(t===this.source)return;let e=new this.window.DOMParser().parseFromString(t,"text/html"),i=this.generation+1,s=e.createElement("script");s.textContent=`(() => {
13
+ `}])):this.submit();else if(["Backspace","Delete"].includes(t.key)&&!e&&!t.altKey){this.captureSelection();let{start:s,end:n}=this.selection,r=t.key==="Backspace"?s-1:s;s===n&&((i=l.slice(this.parts(),r,r+1)[0])==null?void 0:i.type)==="context"&&(t.preventDefault(),this.replace(r,r+1,[]))}}copy(t,e){if(!this.captureSelection()||this.selection.start===this.selection.end)return;let i=l.slice(this.parts(),this.selection.start,this.selection.end);t.clipboardData.setData("text/plain",l.text(i)),t.clipboardData.setData("application/x-pycodex-parts",JSON.stringify(i)),t.preventDefault(),e&&this.replace(this.selection.start,this.selection.end,[])}paste(t){try{let e=t.getData("application/x-pycodex-parts"),i=e?JSON.parse(e):[{type:"text",text:t.getData("text/plain")}];if(!Array.isArray(i)||i.some(s=>!s||typeof s.text!="string"||!["text","context"].includes(s.type)||s.type==="context"&&typeof s.label!="string"))throw new Error("Invalid context format in clipboard.");this.captureSelection(),this.replace(this.selection.start,this.selection.end,i.map(s=>s.type==="context"?{...s,id:crypto.getRandomValues(new Uint32Array(4)).join("-")}:s))}catch(e){this.error(e.message)}}};function K(l){let t=l.trim().match(/^<(clock_tick|exec_command_completed)>\s*([\s\S]*?)\s*<\/\1>$/);if(!t)return!1;try{let e=JSON.parse(t[2]);return e!==null&&typeof e=="object"&&!Array.isArray(e)}catch(e){return!1}}var D=class{constructor(){this.entries=[],this.seen=new Set,this.pending=[],this.index=null,this.draft=null}remember(t){let e=t.parts.map(i=>({...i}));E.text(e).trim()&&(this.append({parts:e}),this.pending.push(E.text(e).trim()),this.pending.length>100&&this.pending.shift(),this.reset())}append(t){this.entries.push(t),this.entries.length>100&&(this.entries.shift(),this.index!==null&&(this.index=Math.max(0,this.index-1)))}update(t){for(let e of t||[]){let i=e.submission_id||e.turn_id;if(!i||this.seen.has(i))continue;this.seen.add(i);let s=e.prompt;if(!s||!s.trim())continue;let n=this.pending.indexOf(s.trim());if(n!==-1){this.pending.splice(n,1);continue}e.kind==="compaction"||K(s)||!["web","cli","feishu","resume","user"].includes(e.sender)||this.append({parts:[{type:"text",text:s}]})}}reset(){this.index=null,this.draft=null}recall(t,e){if(this.index!==null&&JSON.stringify(e.parts)!==JSON.stringify(this.entries[this.index].parts)&&this.reset(),t){if(!this.entries.length||this.index===0)return null;this.index===null&&(this.draft=e,this.index=this.entries.length),this.index-=1}else{if(this.index===null)return null;if(this.index+=1,this.index>=this.entries.length){let i=this.draft;return this.reset(),i}}return{parts:this.entries[this.index].parts.map(i=>({...i}))}}};function it(l,t=!0){if(typeof l!="string"||!l||l!==l.trim()||/[\x00-\x1f\x7f]/.test(l))return!1;if(/^(?:diff:|git:|workspace:\/\/canvas\/?$)/i.test(l))return!0;if(!t||/^(?:https?|ftps?|mailto|tel|sms|javascript|vbscript|data|blob|about|file):/i.test(l))return!1;let e=l.split("#");if(e.length>2||e.length===2&&!/^L-?\d+$/i.test(e[1]))return!1;let i=e[0].replace(/:-?\d+$/,"");return!!i&&!i.startsWith("//")&&!i.includes("?")&&(!/^[a-z][a-z\d+.-]*:/i.test(i)||/^[a-z]:(?:[/\\]|%2f|%5c)/i.test(i))}var P=class{constructor({request:t,onChange:e,onSelect:i,selected:s=null,enableBoard:n=!0}){this.request=t,this.onChange=e,this.onSelect=i,this.enableBoard=n,this.views=[],this.transcripts=new Map,this.activeId=n?"board":null,this.snapshot=null,this.selection=null,this.displayMode=null,this.loading=!1,this.error="",this.closing=new Set,this.cache=new Map,this.initialSelection=s,this.initialized=!1,this.mutation=0,this.pollRequest=null,this.contentRequest=null,this.openRequest=null,this.timer=null}start(){this.timer===null&&(this.poll(),this.timer=setInterval(()=>this.poll(),2e3))}stop(){clearInterval(this.timer),this.timer=null,this.cancelOpen(),this.pollRequest&&this.pollRequest.abort(),this.contentRequest&&this.contentRequest.abort(),this.pollRequest=null,this.contentRequest=null,this.loading=!1}async poll(){if(this.pollRequest||this.openRequest)return;let t=new AbortController,e=this.mutation;this.pollRequest=t;try{let i=await this.request("api/views",{signal:t.signal});if(this.pollRequest!==t||e!==this.mutation)return;this.updateViews(i.views);let s=new Set(this.views.map(r=>r.id));this.error="";let n=this.activeId;this.initialized||(n=this.initialSelection||this.defaultId(),this.initialized=!0),(n==="board"&&!this.enableBoard||n!==null&&n!=="board"&&!s.has(n))&&(n=this.defaultId()),n!==this.activeId||n!==null&&n!=="board"&&!this.snapshot&&!this.loading?this.select(n,null,null,!1):(n!==null&&n!=="board"&&!this.cache.has(n)&&!this.contentRequest&&this.load(n),this.onChange(this))}catch(i){this.pollRequest===t&&e===this.mutation&&i.name!=="AbortError"&&(this.error="Unable to load tabs: "+i.message,this.onChange(this))}finally{this.pollRequest===t&&(this.pollRequest=null)}}defaultId(){return this.enableBoard?"board":this.views.length?this.views[0].id:null}updateViews(t){this.views=t.concat(Array.from(this.transcripts.values()));let e=new Map(this.views.map(i=>[i.id,i.revision]));for(let[i,s]of this.cache)(!e.has(i)||s.revision<e.get(i))&&this.cache.delete(i)}cancelOpen(){this.openRequest&&this.openRequest.abort(),this.openRequest=null}openTranscript(t,e,i){let s=`transcript:${t}:${e}`;if(!this.transcripts.has(s)){let n={id:s,kind:"transcript",title:i,sessionId:t,agentId:e,revision:1,documents:[]};this.transcripts.set(s,n),this.views.push(n),this.cache.set(s,n)}return this.initialized=!0,this.select(s)}async open(t,e,i){if(this.cancelOpen(),/^workspace:\/\/canvas\/?$/i.test(t)){if(!this.enableBoard)throw new Error("Canvas is disabled for this workspace.");await this.select("board");return}let s=new AbortController;this.openRequest=s,this.mutation+=1,this.error="",this.onChange(this);try{let n=await this.request("api/views/open",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({href:t,src_path:e,session_id:i}),signal:s.signal});if(this.openRequest!==s)return;this.mutation+=1,this.updateViews(n.views);let r=n.view;return this.cache.set(r.id,r),this.initialized=!0,this.openRequest=null,this.select(r.id,r.selection?{...r.selection,revision:r.reveal_revision,contentRevision:r.revision}:null,r.selection?"source":"preview")}catch(n){if(this.openRequest!==s||n.name==="AbortError")return;throw this.error="Unable to open view: "+n.message,n}finally{this.openRequest===s&&(this.openRequest=null,this.onChange(this))}}async select(t,e=null,i=null,s=!0){if(t==="board"&&!this.enableBoard||t!==null&&t!=="board"&&!this.views.some(r=>r.id===t))return;this.cancelOpen();let n=t===this.activeId?this.snapshot:null;this.contentRequest&&this.contentRequest.abort(),this.contentRequest=null,this.activeId=t,this.selection=e,this.displayMode=i,this.initialized||(this.initialSelection=t),this.snapshot=this.cache.get(t)||n,this.loading=t!==null&&t!=="board"&&!this.snapshot,this.error="",this.onChange(this),s&&this.onSelect(t),!(t===null||t==="board"||this.cache.has(t))&&await this.load(t)}setDisplayMode(t){!this.snapshot||this.activeId===null||this.activeId==="board"||!["source","preview"].includes(t)||(this.cancelOpen(),this.selection=null,this.displayMode=t,this.onChange(this))}async load(t){let e=new AbortController;this.contentRequest=e;try{let i=await this.request("api/views/"+encodeURIComponent(t),{signal:e.signal});if(this.contentRequest!==e||this.activeId!==t)return;let s=this.views.find(n=>n.id===t);if(!s||i.revision<s.revision)return;this.cache.set(t,i),this.snapshot=i,this.error=""}catch(i){if(this.contentRequest!==e||this.activeId!==t||i.name==="AbortError")return;this.error="Unable to load view: "+i.message}finally{this.contentRequest===e&&(this.contentRequest=null,this.loading=!1,this.onChange(this))}}async close(t){if(!(t===null||t==="board"||this.closing.has(t))){this.cancelOpen(),this.closing.add(t),this.mutation+=1,this.onChange(this);try{this.transcripts.has(t)?this.transcripts.delete(t):await this.request("api/views/"+encodeURIComponent(t),{method:"DELETE"}),this.mutation+=1;let e=this.views.findIndex(i=>i.id===t);this.views=this.views.filter(i=>i.id!==t),this.cache.delete(t),this.activeId===t&&await this.select(e>0?this.views[e-1].id:this.defaultId())}catch(e){this.error="Unable to close tab: "+e.message}finally{this.closing.delete(t),this.onChange(this)}}}};function g(l,t,e,i){let s=l.createElement(t);return s.className=e,i!==void 0&&(s.textContent=i),s}var B=class{constructor(t,e=[0,0]){this.document=t.ownerDocument,this.window=this.document.defaultView,this.position=e,this.generation=0,this.frame=g(this.document,"iframe","snapshot-html"),this.frame.title="HTML preview",this.receive=i=>{if(i.source!==this.frame.contentWindow)return;let s=i.data;!s||s.generation!==this.generation||(s.type==="workspace-preview-ready"?this.frame.contentWindow.postMessage({type:"workspace-preview-restore",generation:this.generation,position:this.position},"*"):s.type==="workspace-preview-scroll"&&Array.isArray(s.position)&&s.position.length===2&&s.position.every(Number.isFinite)&&(this.position=s.position))},this.window.addEventListener("message",this.receive),t.appendChild(this.frame)}update(t){if(t===this.source)return;let e=new this.window.DOMParser().parseFromString(t,"text/html"),i=this.generation+1,s=e.createElement("script");s.textContent=`(() => {
14
14
  const generation = ${i};
15
15
  let restored = false;
16
16
  function report() {
@@ -31,7 +31,7 @@ Click to edit context; Backspace / Delete to remove`,this.element.append(n,docum
31
31
  type: "workspace-preview-ready", generation,
32
32
  }, "*"));
33
33
  })();`,e.head.prepend(s);let n=e.doctype?new this.window.XMLSerializer().serializeToString(e.doctype)+`
34
- `:"";this.frame.srcdoc=n+e.documentElement.outerHTML,this.generation=i,this.source=t}capture(){return this.position}destroy(){this.window.removeEventListener("message",this.receive)}},z=class{constructor({content:t,renderMarkdown:e,loadEditor:i=null,onInsertContext:s=null,onChangeMode:n=null,request:r=null,createHtmlPreview:o=(h,a)=>new B(h,a)}){this.content=t,this.document=t.ownerDocument,this.renderMarkdown=e,this.request=r,this.transcripts=new Map,this.transcript=null,this.onInsertContext=s,this.onChangeMode=n,this.loadEditor=i||(()=>this.loadEditorAssets()),this.editorAssets=null,this.createHtmlPreview=o,this.activeId=null,this.editor=null,this.htmlPreview=null,this.pdfFrame=null,this.generation=0,this.remaining=new Set,this.editorStates=new Map,this.previews=new Map,this.scrollPositions=new Map,this.sourceViews=new Set,this.pendingSelection=null,this.selectionRevision=0}loadEditorAssets(){if(!this.editorAssets){let t=this.document.createElement("link");t.rel="stylesheet",t.href=new URL("./editor.css",import.meta.url).href;let e=new Promise((i,s)=>{t.addEventListener("load",i,{once:!0}),t.addEventListener("error",()=>s(new Error("Editor stylesheet request failed.")),{once:!0})});this.document.head.insertBefore(t,this.document.head.querySelector("[data-pycodex-custom-style]")),this.editorAssets=Promise.all([import("./editor.mjs"),e]).then(([i])=>i).catch(i=>{throw t.remove(),this.editorAssets=null,i})}return this.editorAssets}retain(t){this.remaining=new Set(t);for(let[e,i]of this.transcripts)this.remaining.has(e)||(i.stop(),this.transcripts.delete(e));for(let e of[this.editorStates,this.previews,this.scrollPositions,this.sourceViews])for(let i of e.keys())this.remaining.has(i)||e.delete(i)}clear(t=""){this.generation+=1,this.transcript&&(this.remaining.has(this.activeId)&&this.scrollPositions.set(this.activeId,[this.content.scrollLeft,this.content.scrollTop]),this.transcript.stop(),this.transcript=null),this.editor?(this.remaining.has(this.activeId)&&this.editorStates.set(this.activeId,this.editor.capture()),this.editor.destroy(),this.editor=null):this.htmlPreview?(this.remaining.has(this.activeId)&&this.scrollPositions.set(this.activeId,this.htmlPreview.capture()),this.htmlPreview.destroy(),this.htmlPreview=null):this.remaining.has(this.activeId)&&this.previews.has(this.activeId)&&this.scrollPositions.set(this.activeId,[this.content.scrollLeft,this.content.scrollTop]),this.activeId=null,this.pdfFrame=null,this.content.classList.remove("code-view"),this.content.classList.remove("html-view"),this.content.classList.remove("pdf-view","transcript-view"),this.content.textContent="",t&&this.content.appendChild(g(this.document,"div","content-placeholder",t))}addModeToggle(t,e,i=null){if(!this.onChangeMode)return;let s=g(this.document,"button","content-mode-toggle",e?"Show preview":"Show source");s.type="button",s.title=e?"Show rendered Markdown":"Show Markdown source",s.setAttribute("aria-label",s.textContent),s.addEventListener("click",()=>this.onChangeMode(e?"preview":"source")),t.insertBefore(s,i)}async show(t,e,i=null,s=null){if(e.kind==="transcript"){if(this.activeId===t&&this.transcript)return;this.clear(),this.activeId=t,this.content.classList.add("transcript-view"),this.transcripts.has(t)||this.transcripts.set(t,new T({viewport:this.content,request:this.request,renderMarkdown:this.renderMarkdown,sessionId:e.sessionId,agentId:e.agentId,agentPath:e.title})),this.transcript=this.transcripts.get(t),this.content.appendChild(this.transcript.root);let[f,w]=this.scrollPositions.get(t)||[0,0];this.content.scrollLeft=f,this.content.scrollTop=w,this.transcript.start();return}i&&e.revision<i.contentRevision&&(i=null),this.pendingSelection=i,s==="preview"?this.sourceViews.delete(t):(i||s==="source")&&this.sourceViews.add(t);let n=e.documents[0],r=e.kind==="file"&&!this.sourceViews.has(t),o=r&&/\.(md|markdown)$/i.test(n.label)&&this.renderMarkdown,h=r&&/\.html?$/i.test(n.label),a=e.kind==="file"&&n.media_type==="application/pdf",u=a?new URL(`../api/views/${encodeURIComponent(t)}/pdf?revision=${e.revision}`,import.meta.url).href:null;if(a&&n.error){this.clear(n.error);return}if(this.activeId===t&&this.pdfFrame&&a){this.pdfFrame.src!==u&&(this.pdfFrame.src=u);return}if(this.activeId===t&&this.htmlPreview&&h)return this.htmlPreview.update(n.text);if(this.activeId===t&&this.editor&&!o&&!h&&!a){let f=this.generation;try{await this.editor.update(e),f===this.generation&&await this.applySelection(t,i)}catch(w){if(f===this.generation)throw w}return}this.clear(),this.activeId=t;let d=this.generation;if(a){this.content.classList.add("pdf-view");let f=g(this.document,"div","snapshot-heading");f.appendChild(g(this.document,"span","snapshot-label",n.label));let w=g(this.document,"div","pdf-actions"),x=g(this.document,"a","content-mode-toggle","Open in new tab");x.href=u,x.target="_blank",x.rel="noopener";let c=g(this.document,"a","content-mode-toggle","Download");c.href=u+"&download=true",w.append(x,c),f.appendChild(w),this.pdfFrame=g(this.document,"iframe","snapshot-pdf"),this.pdfFrame.title="PDF preview: "+n.label,this.pdfFrame.src=u,this.content.append(f,this.pdfFrame);return}if(e.kind==="diff"||!n.image_url&&!o&&!h){this.content.classList.add("code-view"),this.content.appendChild(g(this.document,"div","content-placeholder","Loading code viewer\u2026"));try{let f=await this.loadEditor();if(d!==this.generation)return;this.content.textContent="";let w=g(this.document,"div","workspace-editor");this.content.appendChild(w);let x=this.onInsertContext&&(b=>{d===this.generation&&this.activeId===t&&this.onInsertContext(b)}),c=await f.createSnapshotEditor(w,e,this.editorStates.get(t),x);if(d!==this.generation){c.destroy();return}if(this.editor=c,this.onChangeMode&&this.renderMarkdown&&e.kind==="file"&&/\.(md|markdown)$/i.test(n.label)){let b=w.querySelector(".editor-toolbar"),k=b.querySelector(".editor-actions");b.insertBefore(g(this.document,"span","snapshot-stamp","Read only"),k),this.addModeToggle(b,!0,k)}}catch(f){if(d!==this.generation)return;this.content.textContent="",this.content.appendChild(g(this.document,"div","content-placeholder","Unable to load code viewer: "+f.message));return}await this.applySelection(t,i);return}if(h)return this.content.classList.add("html-view"),this.htmlPreview=this.createHtmlPreview(this.content,this.scrollPositions.get(t)),this.htmlPreview.update(n.text);if(!this.previews.has(t)){let f=g(this.document,"div","snapshot"),w=g(this.document,"div","snapshot-heading");if(w.appendChild(g(this.document,"span","snapshot-label",n.label)),w.appendChild(g(this.document,"span","snapshot-stamp","Read only")),o&&this.onChangeMode&&(w.classList.add("markdown-heading"),this.addModeToggle(w,!1)),f.appendChild(w),n.image_url){let x=g(this.document,"img","snapshot-image");x.alt=n.label,f.appendChild(x)}else f.appendChild(g(this.document,"div","snapshot-markdown markdown"));this.previews.set(t,f)}this.content.appendChild(this.previews.get(t));let m=this.content.querySelector(".snapshot-image");if(m&&m.src!==n.image_url&&(m.src=n.image_url),o){let f=this.content.querySelector(".snapshot-markdown");n.source&&f.setAttribute("data-src-path",n.source.path),this.renderMarkdown(f,n.text)}let[S,R]=this.scrollPositions.get(t)||[0,0];this.content.scrollLeft=S,this.content.scrollTop=R}async applySelection(t,e){if(!e||e.revision<=this.selectionRevision)return;let i=this.editor,s=()=>this.activeId===t&&this.editor===i&&this.pendingSelection===e&&e.revision>this.selectionRevision;s()&&await i.revealLine(e.document,e.line,s)&&(this.selectionRevision=e.revision)}};function nt({tabs:l,frame:t,content:e,status:i,request:s,renderMarkdown:n,onInsertContext:r,enableBoard:o=!0}){let h=l.ownerDocument,a=new z({content:e,renderMarkdown:n,onInsertContext:r,request:s,onChangeMode:c=>f.setDisplayMode(c)}),u,d=null,m=!1,S=null,R=null,f;function w(c){let b=h.getElementById("content-tab-"+c);b&&(b.focus({preventScroll:!0}),b.scrollIntoView({block:"nearest",inline:"nearest"}))}function x(c){let b=c.snapshot?c.snapshot.documents.map(p=>p.error):[];i.textContent=[c.error,...b].filter(Boolean).join("; ")||(c.openRequest?"Opening view\u2026":""),i.title=i.textContent,i.hidden=!i.textContent;let k=new Map(Array.from(l.children,p=>[p.dataset.viewId,p])),F=(o?[{id:"board",title:"Canvas",kind:"board"}]:[]).concat(c.views),M=V(c.views.filter(p=>p.kind!=="transcript"));for(let p of c.views)p.kind==="transcript"&&M.set(p.id,{name:p.title.split("/").pop(),description:"Transcript"});M.set("board",{name:"Canvas",description:""}),F.forEach((p,L)=>{let y=k.get(p.id);if(!y){y=g(h,"div","tab content-tab"),y.dataset.viewId=p.id,y.id="content-tab-"+p.id,y.setAttribute("role","tab"),y.setAttribute("aria-controls",p.id==="board"?t.id:e.id);let O=g(h,"span","tab-label content-tab-label");if(O.appendChild(g(h,"span","content-tab-name")),O.appendChild(g(h,"span","content-tab-description")),y.appendChild(O),y.addEventListener("click",()=>f.select(p.id)),y.addEventListener("keydown",v=>{if(v.target!==y)return;let C=(o?["board"]:[]).concat(f.views.map(H=>H.id)),j=C.indexOf(p.id),I=null;v.key==="ArrowRight"&&(I=C[(j+1)%C.length]),v.key==="ArrowLeft"&&(I=C[(j+C.length-1)%C.length]),v.key==="Home"&&(I=C[0]),v.key==="End"&&(I=C[C.length-1]),(v.key==="Enter"||v.key===" ")&&(I=p.id),v.key==="Delete"&&p.id!=="board"&&(v.preventDefault(),f.close(p.id)),I!==null&&(v.preventDefault(),f.select(I),h.getElementById("content-tab-"+I).focus())}),p.id!=="board"){let v=g(h,"button","tab-close content-tab-close");v.type="button",v.title="Close tab",v.setAttribute("aria-label","Close "+p.title),v.innerHTML='<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" aria-hidden="true"><path d="M4 4l8 8M12 4l-8 8"/></svg>',v.addEventListener("click",C=>{C.stopPropagation(),f.close(p.id)}),y.appendChild(v)}}k.delete(p.id);let N=M.get(p.id);y.querySelector(".content-tab-name").textContent=N.name;let U=y.querySelector(".content-tab-description");U.textContent=N.description,U.hidden=!N.description,y.className="tab content-tab"+(p.id===c.activeId?" active":""),y.tabIndex=p.id===c.activeId?0:-1,y.title=p.id==="board"?l.dataset.boardTitle:p.kind==="transcript"?`${p.title}
34
+ `:"";this.frame.srcdoc=n+e.documentElement.outerHTML,this.generation=i,this.source=t}capture(){return this.position}destroy(){this.window.removeEventListener("message",this.receive)}},z=class{constructor({content:t,renderMarkdown:e,loadEditor:i=null,onInsertContext:s=null,onChangeMode:n=null,request:r=null,createHtmlPreview:o=(h,a)=>new B(h,a)}){this.content=t,this.document=t.ownerDocument,this.renderMarkdown=e,this.request=r,this.transcripts=new Map,this.transcript=null,this.onInsertContext=s,this.onChangeMode=n,this.loadEditor=i||(()=>this.loadEditorAssets()),this.editorAssets=null,this.createHtmlPreview=o,this.activeId=null,this.editor=null,this.htmlPreview=null,this.pdfFrame=null,this.generation=0,this.remaining=new Set,this.editorStates=new Map,this.previews=new Map,this.scrollPositions=new Map,this.sourceViews=new Set,this.pendingSelection=null,this.selectionRevision=0}loadEditorAssets(){if(!this.editorAssets){let t=this.document.createElement("link");t.rel="stylesheet",t.href=new URL("./editor.css",import.meta.url).href;let e=new Promise((i,s)=>{t.addEventListener("load",i,{once:!0}),t.addEventListener("error",()=>s(new Error("Editor stylesheet request failed.")),{once:!0})});this.document.head.insertBefore(t,this.document.head.querySelector("[data-pycodex-custom-style]")),this.editorAssets=Promise.all([import("./editor.mjs"),e]).then(([i])=>i).catch(i=>{throw t.remove(),this.editorAssets=null,i})}return this.editorAssets}retain(t){this.remaining=new Set(t);for(let[e,i]of this.transcripts)this.remaining.has(e)||(i.stop(),this.transcripts.delete(e));for(let e of[this.editorStates,this.previews,this.scrollPositions,this.sourceViews])for(let i of e.keys())this.remaining.has(i)||e.delete(i)}clear(t=""){this.generation+=1,this.transcript&&(this.remaining.has(this.activeId)&&this.scrollPositions.set(this.activeId,[this.content.scrollLeft,this.content.scrollTop]),this.transcript.stop(),this.transcript=null),this.editor?(this.remaining.has(this.activeId)&&this.editorStates.set(this.activeId,this.editor.capture()),this.editor.destroy(),this.editor=null):this.htmlPreview?(this.remaining.has(this.activeId)&&this.scrollPositions.set(this.activeId,this.htmlPreview.capture()),this.htmlPreview.destroy(),this.htmlPreview=null):this.remaining.has(this.activeId)&&this.previews.has(this.activeId)&&this.scrollPositions.set(this.activeId,[this.content.scrollLeft,this.content.scrollTop]),this.activeId=null,this.pdfFrame=null,this.content.classList.remove("code-view"),this.content.classList.remove("html-view"),this.content.classList.remove("pdf-view","transcript-view"),this.content.textContent="",t&&this.content.appendChild(g(this.document,"div","content-placeholder",t))}addModeToggle(t,e,i=null){if(!this.onChangeMode)return;let s=g(this.document,"button","content-mode-toggle",e?"Show preview":"Show source");s.type="button",s.title=e?"Show rendered Markdown":"Show Markdown source",s.setAttribute("aria-label",s.textContent),s.addEventListener("click",()=>this.onChangeMode(e?"preview":"source")),t.insertBefore(s,i)}async show(t,e,i=null,s=null){if(e.kind==="transcript"){if(this.activeId===t&&this.transcript)return;this.clear(),this.activeId=t,this.content.classList.add("transcript-view"),this.transcripts.has(t)||this.transcripts.set(t,new T({viewport:this.content,request:this.request,renderMarkdown:this.renderMarkdown,sessionId:e.sessionId,agentId:e.agentId,agentPath:e.title})),this.transcript=this.transcripts.get(t),this.content.appendChild(this.transcript.root);let[f,w]=this.scrollPositions.get(t)||[0,0];this.content.scrollLeft=f,this.content.scrollTop=w,this.transcript.start();return}i&&e.revision<i.contentRevision&&(i=null),this.pendingSelection=i,s==="preview"?this.sourceViews.delete(t):(i||s==="source")&&this.sourceViews.add(t);let n=e.documents[0],r=e.kind==="file"&&!this.sourceViews.has(t),o=r&&/\.(md|markdown)$/i.test(n.label)&&this.renderMarkdown,h=r&&/\.html?$/i.test(n.label),a=e.kind==="file"&&n.media_type==="application/pdf",u=a?new URL(`../api/views/${encodeURIComponent(t)}/pdf?revision=${e.revision}`,import.meta.url).href:null;if(a&&n.error){this.clear(n.error);return}if(this.activeId===t&&this.pdfFrame&&a){this.pdfFrame.src!==u&&(this.pdfFrame.src=u);return}if(this.activeId===t&&this.htmlPreview&&h)return this.htmlPreview.update(n.text);if(this.activeId===t&&this.editor&&!o&&!h&&!a){let f=this.generation;try{await this.editor.update(e),f===this.generation&&await this.applySelection(t,i)}catch(w){if(f===this.generation)throw w}return}this.clear(),this.activeId=t;let d=this.generation;if(a){this.content.classList.add("pdf-view");let f=g(this.document,"div","snapshot-heading");f.appendChild(g(this.document,"span","snapshot-label",n.label));let w=g(this.document,"div","pdf-actions"),x=g(this.document,"a","content-mode-toggle","Open in new tab");x.href=u,x.target="_blank",x.rel="noopener";let c=g(this.document,"a","content-mode-toggle","Download");c.href=u+"&download=true",w.append(x,c),f.appendChild(w),this.pdfFrame=g(this.document,"iframe","snapshot-pdf"),this.pdfFrame.title="PDF preview: "+n.label,this.pdfFrame.src=u,this.content.append(f,this.pdfFrame);return}if(e.kind==="diff"||!n.image_url&&!o&&!h){this.content.classList.add("code-view"),this.content.appendChild(g(this.document,"div","content-placeholder","Loading code viewer\u2026"));try{let f=await this.loadEditor();if(d!==this.generation)return;this.content.textContent="";let w=g(this.document,"div","workspace-editor");this.content.appendChild(w);let x=this.onInsertContext&&(b=>{d===this.generation&&this.activeId===t&&this.onInsertContext(b)}),c=await f.createSnapshotEditor(w,e,this.editorStates.get(t),x);if(d!==this.generation){c.destroy();return}if(this.editor=c,this.onChangeMode&&this.renderMarkdown&&e.kind==="file"&&/\.(md|markdown)$/i.test(n.label)){let b=w.querySelector(".editor-toolbar"),k=b.querySelector(".editor-actions");b.insertBefore(g(this.document,"span","snapshot-stamp","Read only"),k),this.addModeToggle(b,!0,k)}}catch(f){if(d!==this.generation)return;this.content.textContent="",this.content.appendChild(g(this.document,"div","content-placeholder","Unable to load code viewer: "+f.message));return}await this.applySelection(t,i);return}if(h)return this.content.classList.add("html-view"),this.htmlPreview=this.createHtmlPreview(this.content,this.scrollPositions.get(t)),this.htmlPreview.update(n.text);if(!this.previews.has(t)){let f=g(this.document,"div","snapshot"),w=g(this.document,"div","snapshot-heading");if(w.appendChild(g(this.document,"span","snapshot-label",n.label)),w.appendChild(g(this.document,"span","snapshot-stamp","Read only")),o&&this.onChangeMode&&(w.classList.add("markdown-heading"),this.addModeToggle(w,!1)),f.appendChild(w),n.image_url){let x=g(this.document,"img","snapshot-image");x.alt=n.label,f.appendChild(x)}else f.appendChild(g(this.document,"div","snapshot-markdown markdown"));this.previews.set(t,f)}this.content.appendChild(this.previews.get(t));let m=this.content.querySelector(".snapshot-image");if(m&&m.src!==n.image_url&&(m.src=n.image_url),o){let f=this.content.querySelector(".snapshot-markdown");n.source&&f.setAttribute("data-src-path",n.source.path),this.renderMarkdown(f,n.text)}let[S,R]=this.scrollPositions.get(t)||[0,0];this.content.scrollLeft=S,this.content.scrollTop=R}async applySelection(t,e){if(!e||e.revision<=this.selectionRevision)return;let i=this.editor,s=()=>this.activeId===t&&this.editor===i&&this.pendingSelection===e&&e.revision>this.selectionRevision;s()&&await i.revealLine(e.document,e.line,s)&&(this.selectionRevision=e.revision)}};function nt({tabs:l,frame:t,content:e,status:i,request:s,renderMarkdown:n,onInsertContext:r,enableBoard:o=!0}){let h=l.ownerDocument,a=new z({content:e,renderMarkdown:n,onInsertContext:r,request:s,onChangeMode:c=>f.setDisplayMode(c)}),u,d=null,m=!1,S=null,R=null,f;function w(c){let b=h.getElementById("content-tab-"+c);b&&(b.focus({preventScroll:!0}),b.scrollIntoView({block:"nearest",inline:"nearest"}))}function x(c){let b=c.snapshot?c.snapshot.documents.map(p=>p.error):[];i.textContent=[c.error,...b].filter(Boolean).join("; ")||(c.openRequest?"Opening view\u2026":""),i.title=i.textContent,i.hidden=!i.textContent;let k=new Map(Array.from(l.children,p=>[p.dataset.viewId,p])),V=(o?[{id:"board",title:"Canvas",kind:"board"}]:[]).concat(c.views),M=j(c.views.filter(p=>p.kind!=="transcript"));for(let p of c.views)p.kind==="transcript"&&M.set(p.id,{name:p.title.split("/").pop(),description:"Transcript"});M.set("board",{name:"Canvas",description:""}),V.forEach((p,L)=>{let y=k.get(p.id);if(!y){y=g(h,"div","tab content-tab"),y.dataset.viewId=p.id,y.id="content-tab-"+p.id,y.setAttribute("role","tab"),y.setAttribute("aria-controls",p.id==="board"?t.id:e.id);let O=g(h,"span","tab-label content-tab-label");if(O.appendChild(g(h,"span","content-tab-name")),O.appendChild(g(h,"span","content-tab-description")),y.appendChild(O),y.addEventListener("click",()=>f.select(p.id)),y.addEventListener("keydown",v=>{if(v.target!==y)return;let C=(o?["board"]:[]).concat(f.views.map(F=>F.id)),U=C.indexOf(p.id),I=null;v.key==="ArrowRight"&&(I=C[(U+1)%C.length]),v.key==="ArrowLeft"&&(I=C[(U+C.length-1)%C.length]),v.key==="Home"&&(I=C[0]),v.key==="End"&&(I=C[C.length-1]),(v.key==="Enter"||v.key===" ")&&(I=p.id),v.key==="Delete"&&p.id!=="board"&&(v.preventDefault(),f.close(p.id)),I!==null&&(v.preventDefault(),f.select(I),h.getElementById("content-tab-"+I).focus())}),p.id!=="board"){let v=g(h,"button","tab-close content-tab-close");v.type="button",v.title="Close tab",v.setAttribute("aria-label","Close "+p.title),v.innerHTML='<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" aria-hidden="true"><path d="M4 4l8 8M12 4l-8 8"/></svg>',v.addEventListener("click",C=>{C.stopPropagation(),f.close(p.id)}),y.appendChild(v)}}k.delete(p.id);let N=M.get(p.id);y.querySelector(".content-tab-name").textContent=N.name;let J=y.querySelector(".content-tab-description");J.textContent=N.description,J.hidden=!N.description,y.className="tab content-tab"+(p.id===c.activeId?" active":""),y.tabIndex=p.id===c.activeId?0:-1,y.title=p.id==="board"?l.dataset.boardTitle:p.kind==="transcript"?`${p.title}
35
35
  Agent transcript`:p.title+(p.live?`
36
36
  Read only \xB7 follows file changes \xB7 `:`
37
- Read-only snapshot \xB7 `)+new Date(p.created_at).toLocaleString(),y.setAttribute("aria-selected",String(p.id===c.activeId)),y.setAttribute("aria-label",p.title);let _=y.querySelector(".content-tab-close");_&&(_.disabled=c.closing.has(p.id),_.setAttribute("aria-label","Close "+p.title)),l.children[L]!==y&&l.insertBefore(y,l.children[L]||null)}),k.forEach(p=>p.remove()),a.retain(c.views.map(p=>p.id));let q=c.activeId==="board",$=u!==c.activeId,J=$||d!==c.snapshot||m!==c.loading||S!==c.selection||R!==c.displayMode;if(q&&J&&a.clear(),t.hidden=!q,e.hidden=q,!!J&&(u=c.activeId,d=c.snapshot,m=c.loading,S=c.selection,R=c.displayMode,c.activeId?e.setAttribute("aria-labelledby","content-tab-"+c.activeId):e.removeAttribute("aria-labelledby"),e.setAttribute("aria-busy",String(c.loading)),!q)){if(c.snapshot){let p=c.activeId,L=c.snapshot;a.show(p,L,c.selection,c.displayMode).catch(y=>{u!==p||d!==L||(d=null,c.error="Unable to update view: "+y.message,i.textContent=i.title=c.error,i.hidden=!1)})}else a.clear(c.loading?"Loading view\u2026":c.activeId?"View unavailable.":"Open a file link to view it here.");$&&w(c.activeId)}}return f=new P({request:s,enableBoard:o,onChange:x,onSelect:c=>{e.closest(".workspace").dataset.mobilePane="board",w(c)}}),x(f),{start(){f.start(),x(f)},stop(){f.stop(),a.clear(),u=null},poll(){return f.poll()},open(c,b,k){return f.open(c,b,k)},openTranscript(c,b,k){return f.openTranscript(c,b,k)}}}export{E as Composer,P as ContentTabs,D as PromptHistory,z as SnapshotDisplay,it as isWorkspaceLink,nt as mountContentViews};
37
+ Read-only snapshot \xB7 `)+new Date(p.created_at).toLocaleString(),y.setAttribute("aria-selected",String(p.id===c.activeId)),y.setAttribute("aria-label",p.title);let _=y.querySelector(".content-tab-close");_&&(_.disabled=c.closing.has(p.id),_.setAttribute("aria-label","Close "+p.title)),l.children[L]!==y&&l.insertBefore(y,l.children[L]||null)}),k.forEach(p=>p.remove()),a.retain(c.views.map(p=>p.id));let q=c.activeId==="board",$=u!==c.activeId||d!==c.snapshot||m!==c.loading||S!==c.selection||R!==c.displayMode;if(q&&$&&a.clear(),t.hidden=!q,e.hidden=q,!!$&&(u=c.activeId,d=c.snapshot,m=c.loading,S=c.selection,R=c.displayMode,c.activeId?e.setAttribute("aria-labelledby","content-tab-"+c.activeId):e.removeAttribute("aria-labelledby"),e.setAttribute("aria-busy",String(c.loading)),!q))if(c.snapshot){let p=c.activeId,L=c.snapshot;a.show(p,L,c.selection,c.displayMode).catch(y=>{u!==p||d!==L||(d=null,c.error="Unable to update view: "+y.message,i.textContent=i.title=c.error,i.hidden=!1)})}else a.clear(c.loading?"Loading view\u2026":c.activeId?"View unavailable.":"Open a file link to view it here.")}return f=new P({request:s,enableBoard:o,onChange:x,onSelect:c=>{e.closest(".workspace").dataset.mobilePane="board",w(c)}}),x(f),{start(){f.start(),x(f)},stop(){f.stop(),a.clear(),u=null},poll(){return f.poll()},open(c,b,k){return f.open(c,b,k)},openTranscript(c,b,k){return f.openTranscript(c,b,k)}}}export{E as Composer,P as ContentTabs,D as PromptHistory,z as SnapshotDisplay,it as isWorkspaceLink,nt as mountContentViews};
@@ -80,7 +80,7 @@ export class ContentTabs {
80
80
  if ((next === "board" && !this.enableBoard) ||
81
81
  (next !== null && next !== "board" && !remaining.has(next))) next = this.defaultId();
82
82
  if (next !== this.activeId || (next !== null && next !== "board" && !this.snapshot && !this.loading)) {
83
- this.select(next);
83
+ this.select(next, null, null, false);
84
84
  } else {
85
85
  if (next !== null && next !== "board" && !this.cache.has(next) && !this.contentRequest) this.load(next);
86
86
  this.onChange(this);
@@ -168,7 +168,7 @@ export class ContentTabs {
168
168
  }
169
169
  }
170
170
 
171
- async select(id, selection = null, displayMode = null) {
171
+ async select(id, selection = null, displayMode = null, reveal = true) {
172
172
  if (id === "board" && !this.enableBoard) return;
173
173
  if (id !== null && id !== "board" && !this.views.some(view => view.id === id)) return;
174
174
  this.cancelOpen();
@@ -182,8 +182,8 @@ export class ContentTabs {
182
182
  this.snapshot = this.cache.get(id) || current;
183
183
  this.loading = id !== null && id !== "board" && !this.snapshot;
184
184
  this.error = "";
185
- this.onSelect(id);
186
185
  this.onChange(this);
186
+ if (reveal) this.onSelect(id);
187
187
  if (id === null || id === "board" || this.cache.has(id)) return;
188
188
  await this.load(id);
189
189
  }
@@ -743,7 +743,6 @@ export function mountContentViews({
743
743
  display.clear(state.loading ? "Loading view…" :
744
744
  state.activeId ? "View unavailable." : "Open a file link to view it here.");
745
745
  }
746
- if (switched) focusTab(state.activeId);
747
746
  }
748
747
 
749
748
  controller = new ContentTabs({
@@ -371,11 +371,15 @@ def _websocket_backend_hint_response() -> JSONResponse:
371
371
 
372
372
 
373
373
  def _sessions_response(manager: "WorkspaceSessionManager") -> JSONResponse:
374
+ try:
375
+ manager.refresh_profiles()
376
+ except ValueError as exc:
377
+ raise HTTPException(status_code=400, detail=str(exc))
374
378
  return JSONResponse({
375
379
  "sessions": manager.list_sessions(),
376
380
  "profiles": list(manager.profile_factories),
377
381
  "default_profile": manager.default_profile,
378
- })
382
+ }, headers={"Cache-Control": "no-store"})
379
383
 
380
384
 
381
385
  def _read_session_response(
@@ -409,9 +413,10 @@ async def _new_session_response(
409
413
  raise HTTPException(status_code=422, detail="title and prompt must be strings")
410
414
  if profile is not None and not isinstance(profile, str):
411
415
  raise HTTPException(status_code=422, detail="profile must be a string or null")
412
- if profile is not None and profile not in manager.profile_factories:
413
- raise HTTPException(status_code=400, detail="unknown Codex profile: " + profile)
414
- session_id = await manager.create_session(title=title, profile=profile)
416
+ try:
417
+ session_id = await manager.create_session(title=title, profile=profile)
418
+ except ValueError as exc:
419
+ raise HTTPException(status_code=400, detail=str(exc))
415
420
  result = (
416
421
  await manager.get(session_id).submit(prompt, sender="web", name=name)
417
422
  if prompt else {"ok": True}
@@ -61,12 +61,17 @@ class WorkspaceSessionManager:
61
61
  views=None,
62
62
  profile_factories: "typing.Optional[typing.Dict[str, SessionFactory]]" = None,
63
63
  default_profile: "typing.Optional[str]" = None,
64
+ profile_loader=None,
64
65
  ) -> None:
66
+ if profile_loader is not None and (
67
+ profile_factories is not None or default_profile is not None
68
+ ):
69
+ raise ValueError("profile_loader cannot be combined with static profiles")
65
70
  self._session_factory = session_factory
71
+ self._profile_loader = profile_loader
66
72
  self.profile_factories = dict(profile_factories or {})
67
73
  self.default_profile = default_profile
68
- if default_profile is not None and default_profile not in self.profile_factories:
69
- raise ValueError("unknown Codex profile: {0}".format(default_profile))
74
+ self.refresh_profiles()
70
75
  self._sessions: "typing.Dict[str, object]" = {}
71
76
  self._session_order: "typing.List[str]" = []
72
77
  self._state_watchers: "typing.Dict[str, asyncio.Task]" = {}
@@ -81,6 +86,15 @@ class WorkspaceSessionManager:
81
86
  workspace_file_path(state_path, ".pycodex-views.json")
82
87
  )
83
88
 
89
+ def refresh_profiles(self) -> None:
90
+ factories, default = self.profile_factories, self.default_profile
91
+ if self._profile_loader is not None:
92
+ factories, default = self._profile_loader()
93
+ if default is not None and default not in factories:
94
+ raise ValueError("unknown Codex profile: {0}".format(default))
95
+ self.profile_factories = dict(factories)
96
+ self.default_profile = default
97
+
84
98
  def _get_lock(self):
85
99
  if self._lock is None:
86
100
  self._lock = asyncio.Lock()
@@ -93,6 +107,7 @@ class WorkspaceSessionManager:
93
107
  self._persist_callback = callback
94
108
 
95
109
  async def start(self) -> None:
110
+ self.refresh_profiles()
96
111
  state_tabs = self._state_store.load_tabs()
97
112
  if not state_tabs:
98
113
  await self.create_session()
@@ -133,6 +148,7 @@ class WorkspaceSessionManager:
133
148
  rollout_path: str = "",
134
149
  profile: "typing.Optional[str]" = None,
135
150
  ) -> str:
151
+ self.refresh_profiles()
136
152
  session_id = await self._create_session(
137
153
  title, rollout_path,
138
154
  profile=self.default_profile if profile is None else profile,
File without changes
File without changes