akanjs 3.2.0-rc.12 → 3.2.0-rc.13

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 (86) hide show
  1. package/ARCHITECTURE.md +17 -17
  2. package/CHANGELOG.md +18 -0
  3. package/client/csrTypes.ts +2 -0
  4. package/client/index.ts +1 -0
  5. package/client/route/RouteDefinition.ts +24 -7
  6. package/client/route/routeArgs.ts +7 -0
  7. package/client/router.ts +12 -2
  8. package/package.json +1 -1
  9. package/server/akanApp.ts +103 -1270
  10. package/server/akanServer.ts +1 -1
  11. package/server/gateway/childSupervisor.ts +325 -0
  12. package/server/gateway/devHostChannel.ts +40 -0
  13. package/server/gateway/gatewayChildren.ts +135 -0
  14. package/server/gateway/gatewayConfig.ts +182 -0
  15. package/server/gateway/gatewayHttpProxy.ts +231 -0
  16. package/server/gateway/gatewayLogging.ts +111 -0
  17. package/server/gateway/gatewayRooms.ts +134 -0
  18. package/server/gateway/gatewayStatus.ts +116 -0
  19. package/server/gateway/gatewayStatusPage.ts +54 -0
  20. package/server/gateway/gatewayWebSocketRelay.ts +149 -0
  21. package/server/mcp/McpDispatcher.ts +6 -24
  22. package/signal/SignalFailure.ts +21 -0
  23. package/signal/agentTurnStream.ts +5 -2
  24. package/types/client/csrTypes.d.ts +2 -0
  25. package/types/client/index.d.ts +1 -1
  26. package/types/client/route/RouteDefinition.d.ts +2 -2
  27. package/types/client/route/routeArgs.d.ts +6 -0
  28. package/types/client/router.d.ts +2 -1
  29. package/types/server/akanApp.d.ts +2 -20
  30. package/types/server/gateway/childSupervisor.d.ts +33 -0
  31. package/types/server/gateway/devHostChannel.d.ts +13 -0
  32. package/types/server/gateway/gatewayChildren.d.ts +47 -0
  33. package/types/server/gateway/gatewayConfig.d.ts +82 -0
  34. package/types/server/gateway/gatewayHttpProxy.d.ts +22 -0
  35. package/types/server/gateway/gatewayLogging.d.ts +16 -0
  36. package/types/server/gateway/gatewayRooms.d.ts +22 -0
  37. package/types/server/gateway/gatewayStatus.d.ts +62 -0
  38. package/types/server/gateway/gatewayStatusPage.d.ts +9 -0
  39. package/types/server/gateway/gatewayWebSocketRelay.d.ts +17 -0
  40. package/types/server/logging/rotatingLogWriter.d.ts +1 -1
  41. package/types/signal/SignalFailure.d.ts +1 -0
  42. package/types/signal/agentTurnStream.d.ts +1 -0
  43. package/types/ui/Agent/Chat.d.ts +5 -2
  44. package/types/ui/Agent/ChatHeader.d.ts +13 -0
  45. package/types/ui/Agent/ChatPendingCards.d.ts +23 -0
  46. package/types/ui/overlayLayer.d.ts +6 -1
  47. package/types/vendor/@akanjs/native/packages/cli/src/lib/project.d.ts +4 -0
  48. package/types/vendor/@akanjs/native/packages/desktop/src/relaunch.d.ts +1 -0
  49. package/types/vendor/@akanjs/native/plugins/external-view/src/index.d.ts +14 -10
  50. package/types/vendor/use-agentic/failureCode.d.ts +4 -0
  51. package/types/vendor/use-agentic/types.d.ts +6 -0
  52. package/types/webkit/CsrGuards.d.ts +2 -0
  53. package/ui/Agent/Chat.tsx +96 -116
  54. package/ui/Agent/ChatHeader.tsx +59 -0
  55. package/ui/Agent/ChatPendingCards.tsx +49 -0
  56. package/ui/Agent/fetchRunner.ts +8 -1
  57. package/ui/BottomSheet.tsx +1 -1
  58. package/ui/Dialog/LegacyModal.tsx +1 -1
  59. package/ui/Dialog/Modal.tsx +1 -1
  60. package/ui/Popconfirm.tsx +1 -1
  61. package/ui/overlayLayer.ts +22 -1
  62. package/vendor/@akanjs/native/CHANGELOG.md +6 -1
  63. package/vendor/@akanjs/native/native/desktop/src/external.rs +213 -111
  64. package/vendor/@akanjs/native/native/desktop/src/lib.rs +12 -4
  65. package/vendor/@akanjs/native/native/desktop/src/linux/external.rs +275 -0
  66. package/vendor/@akanjs/native/native/desktop/src/linux/mod.rs +1 -0
  67. package/vendor/@akanjs/native/packages/cli/src/lib/native-plugins.ts +5 -3
  68. package/vendor/@akanjs/native/packages/cli/src/lib/project.ts +25 -1
  69. package/vendor/@akanjs/native/packages/desktop/src/deeplinks.ts +2 -2
  70. package/vendor/@akanjs/native/packages/desktop/src/host.ts +2 -2
  71. package/vendor/@akanjs/native/packages/desktop/src/relaunch.ts +8 -3
  72. package/vendor/@akanjs/native/plugins/app/src/desktop.ts +2 -2
  73. package/vendor/@akanjs/native/plugins/autostart/src/desktop.ts +2 -1
  74. package/vendor/@akanjs/native/plugins/external-view/native-plugin.json +4 -1
  75. package/vendor/@akanjs/native/plugins/external-view/src/index.ts +14 -10
  76. package/vendor/use-agentic/AgentSession.ts +11 -11
  77. package/vendor/use-agentic/CHANGELOG.md +6 -0
  78. package/vendor/use-agentic/Compaction.ts +2 -1
  79. package/vendor/use-agentic/ToolRunner.ts +3 -15
  80. package/vendor/use-agentic/Transcript.ts +6 -3
  81. package/vendor/use-agentic/WIRE.md +12 -1
  82. package/vendor/use-agentic/failureCode.ts +44 -0
  83. package/vendor/use-agentic/httpRunner.ts +14 -3
  84. package/vendor/use-agentic/types.ts +6 -0
  85. package/webkit/CsrGuards.ts +7 -2
  86. package/webkit/useLocation.ts +3 -2
@@ -0,0 +1,275 @@
1
+ //! The external-view plugin on WebKitGTK (external.rs). A view lies on a GtkOverlay over its window's page: wry's
2
+ //! build_as_child is X11 only. WebKitGTK has no DevTools Protocol, so `cdp` answers the screenshot desktop.ts asks for
3
+ //! through GTK, a visible view holds the keyboard focus in place of sendKey, and frames are told apart at their
4
+ //! responses, as navigation.rs does for the page.
5
+
6
+ use std::{cell::RefCell, rc::Rc};
7
+
8
+ use gtk::{gdk, glib, prelude::*};
9
+ use webkit2gtk::{
10
+ LoadEvent, NavigationPolicyDecision, NavigationPolicyDecisionExt, NetworkError, PolicyDecisionExt, PolicyDecisionType, PolicyError, ResponsePolicyDecision,
11
+ ResponsePolicyDecisionExt, SettingsExt, SnapshotOptions, SnapshotRegion, URIRequestExt, URIResponseExt, WebContextExt, WebProcessTerminationReason, WebResourceExt,
12
+ WebViewExt, WebsiteDataManagerExtManual, WebsiteDataTypes,
13
+ };
14
+ use wry::{WebView, WebViewBuilder, WebViewBuilderExtUnix, WebViewExtUnix};
15
+
16
+ use crate::{
17
+ external::{admits, event, Bounds, Reply},
18
+ json,
19
+ navigation::{scheme, shown},
20
+ push_event, send, UserEvent,
21
+ };
22
+
23
+ pub(crate) type Cursor = ();
24
+
25
+ /// The page's container: tao's GTK box holds it, and every external view of the window lies on it.
26
+ pub(crate) fn page_layer(vbox: &gtk::Box) -> gtk::Overlay {
27
+ let overlay = gtk::Overlay::new();
28
+ vbox.pack_start(&overlay, true, true, 0);
29
+ overlay.show();
30
+ overlay
31
+ }
32
+
33
+ /// The view in a box of its own on the window's overlay, laid out at `bounds`.
34
+ pub(crate) fn build(builder: WebViewBuilder, window: &tao::window::Window, bounds: Bounds) -> Result<WebView, String> {
35
+ use tao::platform::unix::WindowExtUnix;
36
+ let overlay = window
37
+ .default_vbox()
38
+ .and_then(|vbox| vbox.children().into_iter().find_map(|child| child.downcast::<gtk::Overlay>().ok()))
39
+ .ok_or("external view: the window has no page overlay")?;
40
+ let holder = gtk::Box::new(gtk::Orientation::Vertical, 0);
41
+ //? tao's window.show_all() (its first show, window.show, a reopen) would show a view the page hid.
42
+ holder.set_no_show_all(true);
43
+ overlay.add_overlay(&holder);
44
+ lay_out(&holder, bounds);
45
+ holder.show();
46
+ let webview = builder.build_gtk(&holder).map_err(|e| {
47
+ overlay.remove(&holder);
48
+ format!("external view: {e}")
49
+ })?;
50
+ keep_open(&webview);
51
+ Ok(webview)
52
+ }
53
+
54
+ //? wry destroys a webview on `close`, which WebKit sends for window.close() in a top frame with no history: the view
55
+ //? would go and leave its box over the page, taking its clicks. Windows and macOS ignore the call, so the view does too.
56
+ fn keep_open(webview: &WebView) {
57
+ use glib::translate::IntoGlib;
58
+ let wv = webview.webview();
59
+ // SAFETY: `wv` is a live WebKitWebView, and "close" is a signal of its class.
60
+ unsafe {
61
+ let close = glib::gobject_ffi::g_signal_lookup(b"close\0".as_ptr().cast(), webkit2gtk::WebView::static_type().into_glib());
62
+ glib::gobject_ffi::g_signal_handlers_disconnect_matched(
63
+ wv.as_ptr().cast(),
64
+ glib::gobject_ffi::G_SIGNAL_MATCH_ID,
65
+ close,
66
+ 0,
67
+ std::ptr::null_mut(),
68
+ std::ptr::null_mut(),
69
+ std::ptr::null_mut(),
70
+ );
71
+ }
72
+ }
73
+
74
+ fn holder_of(webview: &WebView) -> Option<gtk::Box> {
75
+ webview.webview().parent().and_then(|parent| parent.downcast::<gtk::Box>().ok())
76
+ }
77
+
78
+ //? GtkOverlay sizes an aligned child to its size request: a filling one follows the window, a placed one stays put.
79
+ fn lay_out(holder: &gtk::Box, bounds: Bounds) {
80
+ let (align, x, y, width, height) = match bounds {
81
+ Bounds::Fill => (gtk::Align::Fill, 0, 0, -1, -1),
82
+ Bounds::At { x, y, width, height } => (gtk::Align::Start, x.round() as i32, y.round() as i32, width.round().max(1.0) as i32, height.round().max(1.0) as i32),
83
+ };
84
+ holder.set_halign(align);
85
+ holder.set_valign(align);
86
+ holder.set_margin_start(x);
87
+ holder.set_margin_top(y);
88
+ holder.set_size_request(width, height);
89
+ }
90
+
91
+ pub(crate) fn place(webview: &WebView, bounds: Bounds) {
92
+ if let Some(holder) = holder_of(webview) {
93
+ lay_out(&holder, bounds);
94
+ }
95
+ }
96
+
97
+ //? The overlay gives each child a window of its own: a hidden view's box would still take the clicks meant for the page.
98
+ pub(crate) fn set_visible(webview: &WebView, visible: bool) {
99
+ if let Some(holder) = holder_of(webview) {
100
+ holder.set_visible(visible);
101
+ }
102
+ }
103
+
104
+ /// Off the overlay; wry destroys the webview itself when it is dropped.
105
+ pub(crate) fn discard(webview: &WebView) {
106
+ let Some(holder) = holder_of(webview) else { return };
107
+ if let Some(overlay) = holder.parent().and_then(|parent| parent.downcast::<gtk::Container>().ok()) {
108
+ overlay.remove(&holder);
109
+ }
110
+ }
111
+
112
+ pub(crate) fn reclaim(_page: &WebView) {}
113
+
114
+ pub(crate) fn set_cursor_hidden(_webview: &WebView, _hidden: bool, _cursor: &Cursor) {}
115
+
116
+ pub(crate) fn track_frames(_webview: &WebView, _view: &str, _cursor: &Cursor) {}
117
+
118
+ pub(crate) fn set_muted(webview: &WebView, muted: bool) -> Result<(), String> {
119
+ webview.webview().set_is_muted(muted);
120
+ Ok(())
121
+ }
122
+
123
+ //? wry's clear_all_browsing_data does not wait for WebKit: a reload right after it would still find the old storage.
124
+ pub(crate) fn clear_data(webview: &WebView, reply: Reply) {
125
+ let Some(manager) = webview.webview().context().and_then(|context| context.website_data_manager()) else {
126
+ return reply.send(Err("clearData: the view has no data of its own".into()));
127
+ };
128
+ manager.clear(WebsiteDataTypes::ALL, glib::TimeSpan::from_seconds(0), None::<&gtk::gio::Cancellable>, move |done| {
129
+ reply.send(done.map(|()| "null".into()).map_err(|e| format!("clearData: {e}")));
130
+ });
131
+ }
132
+
133
+ /// The top level stays on `allow`, checked once its response says it is the top-level document; frames load web
134
+ /// content from anywhere; any other scheme (mailto:, another app's) goes nowhere, in any frame.
135
+ pub(crate) fn guard(webview: &WebView, view: &str, allow: Rc<RefCell<Vec<String>>>) {
136
+ let wv = webview.webview();
137
+ //? A history load restored from the page cache commits with no response to check below.
138
+ if let Some(settings) = WebViewExt::settings(&wv) {
139
+ settings.set_enable_page_cache(false);
140
+ }
141
+ //? A failed load's error page commits at the failing URL with no response to check below, and runs the init script
142
+ //? there; one with TLS errors would also report its URL. Both are connected before watch's, so they stop it too.
143
+ let (failed_allow, failed_view) = (allow.clone(), view.to_string());
144
+ wv.connect_load_failed(move |_, _, url, error| {
145
+ if admits(&failed_allow.borrow(), url, false) {
146
+ return false;
147
+ }
148
+ if !error.matches(PolicyError::FrameLoadInterruptedByPolicyChange) && !error.matches(NetworkError::Cancelled) {
149
+ log!("external view {failed_view}: refused the error page of {}, which is on no origin it was opened for", shown(url));
150
+ }
151
+ true
152
+ });
153
+ let tls_allow = allow.clone();
154
+ wv.connect_load_failed_with_tls_errors(move |_, url, _, _| !admits(&tls_allow.borrow(), url, false));
155
+ let view = view.to_string();
156
+ wv.connect_decide_policy(move |_, decision, kind| match kind {
157
+ PolicyDecisionType::NavigationAction => {
158
+ let Some(action) = decision.dynamic_cast_ref::<NavigationPolicyDecision>().and_then(|d| d.navigation_action()) else { return false };
159
+ let url = action.request().and_then(|r| r.uri()).map(|u| u.to_string()).unwrap_or_default();
160
+ if scheme(&url).is_some_and(|s| crate::contract::FRAME_SCHEMES.contains(&s.as_str())) {
161
+ return false;
162
+ }
163
+ log!("external view {view}: refused a navigation to {}", shown(&url));
164
+ decision.ignore();
165
+ true
166
+ }
167
+ PolicyDecisionType::Response => {
168
+ let Some(response) = decision.dynamic_cast_ref::<ResponsePolicyDecision>() else { return false };
169
+ let url = response.response().and_then(|r| r.uri()).map(|u| u.to_string()).unwrap_or_default();
170
+ if !response.is_main_frame_main_resource() || admits(&allow.borrow(), &url, false) {
171
+ return false;
172
+ }
173
+ log!("external view {view}: refused a navigation to {url}, which is on no origin it was opened for");
174
+ decision.ignore();
175
+ true
176
+ }
177
+ _ => false,
178
+ });
179
+ }
180
+
181
+ /// A navigation that failed (the network, DNS, a certificate, a server's error status) and the web process ending.
182
+ /// WebKitGTK reports no console without a script in the page, which the view never runs.
183
+ pub(crate) fn watch(webview: &WebView, view: &str, window: u32, _console: bool) {
184
+ let wv = webview.webview();
185
+ let failed = move |view: &str, url: &str, code: &str| {
186
+ push_event(&event(view, window, &format!(r#""event":"loadFailed","url":{},"errorCode":"{code}""#, json::quote(url))));
187
+ };
188
+ let failed_view = view.to_string();
189
+ wv.connect_load_failed(move |_, _, url, error| {
190
+ //? A navigation refused above and one a newer navigation replaced end so: neither is a failure.
191
+ //? WebKit sends one with TLS errors here too, once load-failed-with-tls-errors below has reported it.
192
+ if error.matches(PolicyError::FrameLoadInterruptedByPolicyChange) || error.matches(NetworkError::Cancelled) || error.kind::<gtk::gio::TlsError>().is_some() {
193
+ return false;
194
+ }
195
+ failed(&failed_view, url, &error_name(error));
196
+ false
197
+ });
198
+ let tls_view = view.to_string();
199
+ wv.connect_load_failed_with_tls_errors(move |_, url, _, _| {
200
+ failed(&tls_view, url, "certificate");
201
+ false
202
+ });
203
+ let status_view = view.to_string();
204
+ wv.connect_load_changed(move |wv, load| {
205
+ if load != LoadEvent::Finished {
206
+ return;
207
+ }
208
+ let Some(response) = wv.main_resource().and_then(|r| r.response()) else { return };
209
+ let status = response.status_code();
210
+ if status >= 400 {
211
+ let url = response.uri().map(|u| u.to_string()).unwrap_or_default();
212
+ failed(&status_view, &url, &format!("http{status}"));
213
+ }
214
+ });
215
+ let gone_view = view.to_string();
216
+ wv.connect_web_process_terminated(move |_, reason| {
217
+ let reason = match reason {
218
+ WebProcessTerminationReason::ExceededMemoryLimit => "oom",
219
+ WebProcessTerminationReason::TerminatedByApi => "killed",
220
+ _ => "crashed",
221
+ };
222
+ send(UserEvent::ExternalGone { view: gone_view.clone(), reason });
223
+ });
224
+ }
225
+
226
+ /// The names WebView2's statuses get on Windows (win/external.rs), for the failures WebKitGTK tells apart.
227
+ fn error_name(error: &glib::Error) -> String {
228
+ use gtk::gio::{IOErrorEnum, ResolverError};
229
+ if error.kind::<ResolverError>().is_some() {
230
+ return "hostNameNotResolved".into();
231
+ }
232
+ match error.kind::<IOErrorEnum>() {
233
+ Some(IOErrorEnum::ConnectionRefused) => "cannotConnect".into(),
234
+ Some(IOErrorEnum::TimedOut) => "timeout".into(),
235
+ Some(IOErrorEnum::HostUnreachable | IOErrorEnum::NetworkUnreachable) => "serverUnreachable".into(),
236
+ Some(IOErrorEnum::BrokenPipe) => "connectionReset".into(),
237
+ _ => {
238
+ log!("external view: a load failed: {error}");
239
+ "unknown".into()
240
+ }
241
+ }
242
+ }
243
+
244
+ /// The one DevTools Protocol method desktop.ts sends here: sendKey is not declared on Linux (focus, below).
245
+ pub(crate) fn cdp(webview: &WebView, method: &str, _params: &str, reply: Reply) {
246
+ match method {
247
+ "Page.captureScreenshot" => capture(webview, reply),
248
+ _ => reply.send(Err(format!("UNSUPPORTED: {method} reaches no view on Linux"))),
249
+ }
250
+ }
251
+
252
+ /// What the view shows, as Page.captureScreenshot answers it: a base64 PNG in `data`.
253
+ fn capture(webview: &WebView, reply: Reply) {
254
+ webview.webview().snapshot(SnapshotRegion::Visible, SnapshotOptions::NONE, None::<&gtk::gio::Cancellable>, move |shot| {
255
+ let png = shot.map_err(|e| format!("capture: {e}")).and_then(|surface| {
256
+ let image = gtk::cairo::ImageSurface::try_from(surface).map_err(|_| "capture: the view answered no image".to_string())?;
257
+ let pixbuf = gdk::pixbuf_get_from_surface(&image, 0, 0, image.width(), image.height()).ok_or("capture: the view answered an empty image")?;
258
+ pixbuf.save_to_bufferv("png", &[]).map_err(|e| format!("capture: {e}"))
259
+ });
260
+ reply.send(png.map(|bytes| format!(r#"{{"data":"{}"}}"#, glib::base64_encode(&bytes))));
261
+ });
262
+ }
263
+
264
+ //? WebKitGTK has no trusted input to send a view, so keys reach it as the user's own: through the keyboard focus.
265
+ pub(crate) fn focus(webview: &WebView) {
266
+ webview.webview().grab_focus();
267
+ }
268
+
269
+ /// The page of the window `any` (the page itself or a view over it) takes the keyboard back.
270
+ pub(crate) fn focus_page(any: &WebView) {
271
+ let page = any.webview().ancestor(gtk::Overlay::static_type()).and_then(|o| o.downcast::<gtk::Overlay>().ok()).and_then(|o| o.child());
272
+ if let Some(page) = page {
273
+ page.grab_focus();
274
+ }
275
+ }
@@ -12,6 +12,7 @@ pub mod clipboard;
12
12
  pub mod device;
13
13
  pub mod dialogs;
14
14
  mod dock;
15
+ pub mod external;
15
16
  mod hotkey;
16
17
  pub mod keychain;
17
18
  pub mod kiosk;
@@ -7,7 +7,7 @@ import { pluginBindings } from "./codegen.ts";
7
7
  import { CliError } from "./log.ts";
8
8
  import { mergePlist } from "./nativeconfig.ts";
9
9
  import type { PlistValue } from "./plist.ts";
10
- import type { AndroidManifest, IosManifest, NativeSubset, ResolvedPlugin } from "./project.ts";
10
+ import type { AndroidManifest, DesktopManifest, IosManifest, NativeSubset, ResolvedPlugin } from "./project.ts";
11
11
 
12
12
  export type NativePlatform = "macos" | "windows" | "linux" | "ios" | "android";
13
13
 
@@ -16,7 +16,8 @@ export function pluginDecls(plugins: ResolvedPlugin[], platform: NativePlatform)
16
16
  const decls: Record<string, PluginDecl> = {};
17
17
  for (const { manifest } of plugins) {
18
18
 
19
- const entry = platform === "ios" || platform === "android" ? manifest[platform] : manifest.desktop;
19
+ const mobile = platform === "ios" || platform === "android";
20
+ const entry = mobile ? manifest[platform] : manifest.desktop;
20
21
  if (entry === undefined || entry === null) continue;
21
22
  if (entry === "web") {
22
23
  if (manifest.web) decls[manifest.id] = "web";
@@ -25,8 +26,9 @@ export function pluginDecls(plugins: ResolvedPlugin[], platform: NativePlatform)
25
26
  const subset: NativeSubset = typeof entry === "string" ? {} : entry;
26
27
  const events = subset.events ?? manifest.events;
27
28
  const coalesce = (manifest.coalesce ?? []).filter((e) => events.includes(e));
29
+ const lacks = mobile ? [] : ((subset as DesktopManifest).unsupported?.[platform] ?? []);
28
30
  decls[manifest.id] = {
29
- methods: subset.methods ?? manifest.methods,
31
+ methods: (subset.methods ?? manifest.methods).filter((m) => !lacks.includes(m)),
30
32
  events,
31
33
  ...(subset.web && manifest.web ? { web: true as const } : {}),
32
34
  ...(coalesce.length ? { coalesce } : {}),
@@ -406,9 +406,14 @@ export interface AndroidManifest extends NativeSubset {
406
406
  minSdk?: number;
407
407
  }
408
408
 
409
+ export const DESKTOP_OSES = ["macos", "windows", "linux"] as const;
410
+ export type DesktopOs = (typeof DESKTOP_OSES)[number];
411
+
409
412
  /** Desktop Bun module that implements only some methods (the rest are UNSUPPORTED, or web with `web: true`). */
410
413
  export interface DesktopManifest extends NativeSubset {
411
414
  module: string;
415
+ /** The methods one desktop OS lacks: left out of that OS's declaration, so `isSupported()` is false there only. */
416
+ unsupported?: Partial<Record<DesktopOs, string[]>>;
412
417
  }
413
418
 
414
419
  export interface PluginManifest {
@@ -536,6 +541,25 @@ export function resolvePlugins(appDir: string, specs: string[], resolveFrom = ap
536
541
  }
537
542
  if (!Array.isArray(manifest.methods) || !Array.isArray(manifest.events ?? []))
538
543
  throw new CliError(`plugin ${spec}: methods and events must be arrays`);
544
+ const desktop = typeof manifest.desktop === "object" && manifest.desktop ? manifest.desktop : undefined;
545
+ if (desktop?.unsupported !== undefined) {
546
+ const declared = desktop.methods ?? manifest.methods;
547
+ const lists = desktop.unsupported as Record<string, unknown> | null;
548
+ const valid =
549
+ !!lists &&
550
+ typeof lists === "object" &&
551
+ !Array.isArray(lists) &&
552
+ Object.entries(lists).every(
553
+ ([os, names]) =>
554
+ (DESKTOP_OSES as readonly string[]).includes(os) &&
555
+ Array.isArray(names) &&
556
+ names.every((name) => typeof name === "string" && declared.includes(name)),
557
+ );
558
+ if (!valid)
559
+ throw new CliError(
560
+ `plugin ${spec}: desktop.unsupported must map macos, windows or linux to methods of its desktop entry`,
561
+ );
562
+ }
539
563
  manifest.events ??= [];
540
564
 
541
565
  for (const [kind, names] of [
@@ -608,7 +632,7 @@ const MANIFEST_KEYS: Record<string, readonly string[]> = {
608
632
  "maven",
609
633
  "minSdk",
610
634
  ],
611
- desktop: ["methods", "events", "web", "module"],
635
+ desktop: ["methods", "events", "web", "module", "unsupported"],
612
636
  macos: ["infoPlist"],
613
637
  };
614
638
 
@@ -3,6 +3,7 @@
3
3
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
4
4
  import { homedir } from "node:os";
5
5
  import { dirname, join } from "node:path";
6
+ import { appLauncher } from "./relaunch.ts";
6
7
 
7
8
  type Env = Record<string, string | undefined>;
8
9
  type Runner = (argv: string[]) => Promise<{ code: number; stdout: string }>;
@@ -158,8 +159,7 @@ export async function registerDeepLinks(
158
159
  const platform = options.platform ?? process.platform;
159
160
  if (!schemes.length || (platform !== "win32" && platform !== "linux")) return;
160
161
  const env = options.env ?? process.env;
161
-
162
- const exe = options.exe ?? (env.APPIMAGE || process.execPath);
162
+ const exe = options.exe ?? appLauncher(env);
163
163
  const runner = options.run ?? run;
164
164
  if (platform === "win32") await registerWindows(app, exe, schemes, runner);
165
165
  else await registerLinux(app, exe, schemes, { env, home: options.home ?? homedir(), runner, icon: options.icon });
@@ -14,7 +14,7 @@ import { cstr, FRAME_EVENT, FRAME_HEADER, FRAME_IPC, openNative, resolvePaths }
14
14
  import { createLifecycle } from "./lifecycle.ts";
15
15
  import { appDataDir, appLocalDataDir, reservedDirs, serverDataDir } from "./paths.ts";
16
16
  import { type DesktopPlugin, useShellOpenLimit } from "./plugin.ts";
17
- import { nextRelaunchDelay, relaunchAfterExit } from "./relaunch.ts";
17
+ import { appLauncher, nextRelaunchDelay, relaunchAfterExit } from "./relaunch.ts";
18
18
  import { createSecretStore } from "./secretStore.ts";
19
19
  import {
20
20
  createDesktopServer,
@@ -350,7 +350,7 @@ export function startHost(plugins: DesktopPlugin[]): void {
350
350
  void lifecycle.quit(1);
351
351
  return;
352
352
  }
353
- relaunchAfterExit(process.execPath, [], { delayMs })
353
+ relaunchAfterExit(appLauncher(), [], { delayMs })
354
354
  .then(() => lifecycle.quit(0))
355
355
  .catch((error: unknown) => console.error("[akan-native] cannot relaunch the app", error));
356
356
  };
@@ -3,7 +3,7 @@
3
3
  import { spawn } from "node:child_process";
4
4
  import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
5
5
  import { tmpdir } from "node:os";
6
- import { dirname } from "node:path";
6
+ import { dirname, resolve } from "node:path";
7
7
 
8
8
  export interface RelaunchOptions {
9
9
  /** How long the helper waits after this process exited before it starts the app. */
@@ -48,6 +48,12 @@ export function recoveryCommand(script: string): string | null {
48
48
  return command.length <= 260 ? command : null;
49
49
  }
50
50
 
51
+ export const appLauncher = (env: NodeJS.ProcessEnv = process.env, exe = process.execPath): string =>
52
+ env.APPIMAGE && env.APPDIR && exe.startsWith(`${resolve(env.APPDIR)}/`) ? env.APPIMAGE : exe;
53
+
54
+ const NOT_INHERITED = new Set(["AKAN_NATIVE_QUIT_ON_STDIN", "APPDIR", "APPIMAGE", "ARGV0", "OWD"]);
55
+ const inheritedEnv = () => Object.fromEntries(Object.entries(process.env).filter(([key]) => !NOT_INHERITED.has(key)));
56
+
51
57
  let started: Promise<void> | null = null;
52
58
 
53
59
  /**
@@ -82,8 +88,7 @@ function startHelper(
82
88
  recover: RelaunchOptions["recover"],
83
89
  start: boolean,
84
90
  ): Promise<void> {
85
-
86
- const { AKAN_NATIVE_QUIT_ON_STDIN: _cli, ...inherited } = process.env;
91
+ const inherited = inheritedEnv();
87
92
  const delay = (delayMs / 1000).toFixed(3);
88
93
  if (process.platform !== "win32") {
89
94
  const done: [string, string][] = [];
@@ -8,7 +8,7 @@ import {
8
8
  linkClaimed,
9
9
  type QuitReason,
10
10
  } from "../../../packages/desktop/src/plugin.ts";
11
- import { relaunchAfterExit } from "../../../packages/desktop/src/relaunch.ts";
11
+ import { appLauncher, relaunchAfterExit } from "../../../packages/desktop/src/relaunch.ts";
12
12
  import type { AppApi, AppEvents } from "./index.ts";
13
13
 
14
14
  const quitVeto = createPageVeto<{ reason: QuitReason }>();
@@ -47,7 +47,7 @@ export default defineDesktopPlugin<AppApi, AppEvents>({
47
47
  setTimeout(() => ctx.quit(0), 50);
48
48
  },
49
49
  relaunch: async (_args, ctx) => {
50
- await relaunchAfterExit(process.execPath);
50
+ await relaunchAfterExit(appLauncher());
51
51
  setTimeout(() => ctx.quit(0), 50);
52
52
  },
53
53
  answerBeforeQuit: (args, ctx) => quitVeto.answer(args, ctx.window),
@@ -5,6 +5,7 @@ import { homedir } from "node:os";
5
5
  import { join } from "node:path";
6
6
  import { AkanNativeError } from "../../../packages/core/src/index.ts";
7
7
  import { type DesktopContext, defineDesktopPlugin } from "../../../packages/desktop/src/plugin.ts";
8
+ import { appLauncher } from "../../../packages/desktop/src/relaunch.ts";
8
9
  import type { AutostartApi, AutostartState, AutostartStatus } from "./index.ts";
9
10
 
10
11
  export interface ShellError {
@@ -111,7 +112,7 @@ export function entryStatus(text: string | null): AutostartStatus {
111
112
  /** `executable`: the file the entry starts; an AppImage's mount point changes at every start, $APPIMAGE does not. */
112
113
  export function linuxAutostart(
113
114
  dir: () => string = () => autostartDir(),
114
- executable: () => string = () => process.env.APPIMAGE || process.execPath,
115
+ executable: () => string = () => appLauncher(),
115
116
  ) {
116
117
  const file = (ctx: DesktopContext) => join(dir(), `${ctx.app.id}.desktop`);
117
118
  const read = (ctx: DesktopContext) => (existsSync(file(ctx)) ? readFileSync(file(ctx), "utf8") : null);
@@ -17,7 +17,10 @@
17
17
  ],
18
18
  "events": ["load", "loadFailed", "gone", "consoleMessage"],
19
19
  "web": null,
20
- "desktop": "./src/desktop.ts",
20
+ "desktop": {
21
+ "module": "./src/desktop.ts",
22
+ "unsupported": { "macos": ["sendKey", "setMuted", "capture"], "linux": ["sendKey"] }
23
+ },
21
24
  "ios": null,
22
25
  "android": null
23
26
  }
@@ -10,8 +10,10 @@ import { definePlugin, type FileRef } from "../../../packages/core/src/index.ts"
10
10
  * permissions and links another program would open (`mailto:`, a custom scheme) are refused. Listing the plugin in
11
11
  * `native.plugins` is what lets an app open one.
12
12
  *
13
- * Windows has every method. macOS (14 or later, for its separate profile) has all but `sendKey`, `setMuted` and
14
- * `capture`, and sends no `loadFailed` or `consoleMessage`. Linux, iOS and Android: UNSUPPORTED.
13
+ * Windows has every method. Linux has all but `sendKey` and sends no `consoleMessage`; there the visible view shown
14
+ * last holds the keyboard focus inside its window, so keys reach it as the user's own, until a click on the page takes
15
+ * the focus or the view is hidden or closed. macOS (14 or later, for its separate profile) has all but `sendKey`,
16
+ * `setMuted` and `capture`, and sends no `loadFailed` or `consoleMessage`. iOS and Android: UNSUPPORTED.
15
17
  */
16
18
  export type ExternalViewBounds = "fill" | { x: number; y: number; width: number; height: number };
17
19
 
@@ -30,7 +32,7 @@ export interface ExternalViewOpenOptions {
30
32
  * with `evaluate`. It may not declare `__akanTopOnly`, and an empty one registers nothing.
31
33
  */
32
34
  initScript?: string;
33
- /** Windows only: macOS refuses `true` as UNSUPPORTED. */
35
+ /** macOS refuses `true` as UNSUPPORTED. */
34
36
  muted?: boolean;
35
37
  /** Media plays with sound without a gesture first (default true): nobody taps a signage screen. */
36
38
  autoplay?: boolean;
@@ -53,7 +55,7 @@ export interface ExternalViewApi {
53
55
  /**
54
56
  * Opens the view, or brings an open one with this id to these options (a page that mounts again finds it). Another
55
57
  * `initScript` builds the view again and loads its page anew, as does another `console` on Windows and another
56
- * `autoplay` on macOS; Windows refuses another `autoplay` as UNSUPPORTED, before anything is built.
58
+ * `autoplay` on macOS and Linux; Windows refuses another `autoplay` as UNSUPPORTED, before anything is built.
57
59
  */
58
60
  open(args: ExternalViewOpenOptions): Promise<ExternalViewState>;
59
61
  /** Rejects NOT_ALLOWED for a URL on none of its `allowOrigins`. */
@@ -72,11 +74,11 @@ export interface ExternalViewApi {
72
74
  evaluate(args: { id: string; script: string }): Promise<{ value: unknown }>;
73
75
  /** A trusted key press (`{ key: "z", code: "KeyZ" }`), whether or not the view has the focus. Windows only. */
74
76
  sendKey(args: { id: string; key: string; code: string }): Promise<void>;
75
- /** The view's own sound only; the system volume is the volume plugin's. Windows only. */
77
+ /** The view's own sound only; the system volume is the volume plugin's. Not on macOS. */
76
78
  setMuted(args: { id: string; muted: boolean }): Promise<void>;
77
79
  /** Clears the view's cookies, storage and cache; the app's own stay. */
78
80
  clearData(args: { id: string }): Promise<void>;
79
- /** A PNG of the view's content (not the screen), kept until its next capture or the next launch. Windows only. */
81
+ /** A PNG of the view's content (not the screen), kept until its next capture or the next launch. Not on macOS. */
80
82
  capture(args: { id: string }): Promise<FileRef & { width?: number; height?: number }>;
81
83
  }
82
84
 
@@ -85,13 +87,15 @@ export interface ExternalViewEvents {
85
87
  /**
86
88
  * A navigation that failed. `errorCode`: `http<status>` for a server's 4xx or 5xx page, else WebView2's own
87
89
  * (`hostNameNotResolved`, `cannotConnect`, `timeout`, `certificate`, `disconnected`, …; a refused connection is
88
- * `unknown`). Windows only.
90
+ * `unknown`). Linux names the same failures by those names (a refused connection is `cannotConnect`) and any other
91
+ * `unknown`. Not on macOS.
89
92
  */
90
93
  loadFailed: { id: string; url: string; errorCode: string };
91
94
  /**
92
- * Its web process ended (`reason`: `crashed`, `unresponsive` or `browserExited` on Windows, `terminated` on macOS);
93
- * the view loads its page again by itself, sooner the first times, and an end while that waits is not reported
94
- * again. `rebuildFailed`: after its browser exited the view could not be built again, and is closed; open it again.
95
+ * Its web process ended (`reason`: `crashed`, `unresponsive` or `browserExited` on Windows, `terminated` on macOS,
96
+ * `crashed`, `killed` or `oom` on Linux); the view loads its page again by itself, sooner the first times, and an end
97
+ * while that waits is not reported again. `rebuildFailed`: after its browser exited the view could not be built
98
+ * again, and is closed; open it again.
95
99
  */
96
100
  gone: { id: string; reason: string; restarts: number };
97
101
  /** `dropped`: messages left out before this one, past the rate cap. Windows only. */
@@ -10,6 +10,7 @@ import type {
10
10
  ContextBlock,
11
11
  MessageReference,
12
12
  PublishedTool,
13
+ RunnerEvent,
13
14
  RunnerRequest,
14
15
  SurfaceView,
15
16
  ToolActivity,
@@ -429,15 +430,15 @@ export class AgentSession {
429
430
  budget = turn + maxTurns;
430
431
  }
431
432
  await this.#autoCompact(controller.signal);
432
- const { toolCalls, stop, overflow } = await this.#assistantTurn(controller.signal);
433
+ const { toolCalls, stop, failure } = await this.#assistantTurn(controller.signal);
433
434
 
434
435
  if (controller.signal.aborted) {
435
436
  this.#unanswered(toolCalls);
436
437
  return;
437
438
  }
438
- if (overflow) {
439
- if (recovered || !(await this.#recover(overflow, controller.signal))) {
440
- if (!controller.signal.aborted) this.#fail(overflow.message);
439
+ if (failure) {
440
+ if (!failure.overflow || recovered || !(await this.#recover(failure.overflow, controller.signal))) {
441
+ if (!controller.signal.aborted) this.#fail(failure.message, failure.code);
441
442
  return;
442
443
  }
443
444
  recovered = true;
@@ -750,7 +751,7 @@ export class AgentSession {
750
751
 
751
752
  async #assistantTurn(
752
753
  signal: AbortSignal,
753
- ): Promise<{ toolCalls: ToolCallRequest[]; stop: TurnStop; overflow?: { message: string; limit?: number } }> {
754
+ ): Promise<{ toolCalls: ToolCallRequest[]; stop: TurnStop; failure?: Extract<RunnerEvent, { type: "error" }> }> {
754
755
  const frame = this.#frame();
755
756
  this.#overhead = AgentSession.#tokensOfFrame(frame);
756
757
  this.#listed = frame.tools.map((tool) => tool.name);
@@ -770,9 +771,7 @@ export class AgentSession {
770
771
  stop = event.stop;
771
772
  usage = event.usage;
772
773
  if (event.limits) this.#limits = { ...this.#limits, ...event.limits };
773
- } else if (event.overflow)
774
- return { toolCalls: [], stop: "end", overflow: { message: event.message, limit: event.overflow.limit } };
775
- else throw new Error(event.message);
774
+ } else return { toolCalls: [], stop: "end", failure: event };
776
775
  }
777
776
  if (toolCalls.length || usage)
778
777
  this.#patchLast({ ...(toolCalls.length ? { toolCalls } : {}), ...(usage ? { usage } : {}) });
@@ -907,10 +906,11 @@ export class AgentSession {
907
906
  }
908
907
 
909
908
  /** Recorded on the open assistant draft when there is one, so a failed turn reads as that turn failing. */
910
- #fail(message: string) {
909
+ #fail(message: string, code?: string) {
910
+ const failed = { error: message, ...(code ? { errorCode: code } : {}) };
911
911
  const last = this.#messages[this.#messages.length - 1];
912
- if (last?.role === "assistant" && !last.error) this.#patchLast({ error: message });
913
- else this.#append({ role: "assistant", error: message });
912
+ if (last?.role === "assistant" && !last.error) this.#patchLast(failed);
913
+ else this.#append({ role: "assistant", ...failed });
914
914
  }
915
915
 
916
916
  #append(message: ChatMessage) {
@@ -4,6 +4,12 @@
4
4
 
5
5
  ### Patch Changes
6
6
 
7
+ - 8c70603: A failed agent turn now names a code a host can branch on, beside the message it already sent, which is unchanged. No upgrade step is needed: the fields are new.
8
+
9
+ - The relay's `error` event and `AgentTurnStream.failure` carry `code`, named the way a failed MCP tool call is. That is the `Err`'s dictionary key, else an `AkanError`'s own code, else the status's name. A guard's 401 or 403 is named by its status alone, and a 5xx never takes a duck-typed body's code. `SignalFailure.codeOf(error, status)` holds that rule, and a failed MCP tool call is now named through it too.
10
+ - `use-agentic`'s `RunnerEvent` error gains an optional `code`. `httpRunner` reads it from a stream's error event and keeps it only when it is a dictionary key or one camelCase token. A failure answered before the stream opens is named by its body's bounded code, else by its status. A 401 or 403 takes no dictionary key there either, so a refusal reads the same before and after the stream opens.
11
+ - The in-page chat keeps the key as `code` after translating the message. The session records it on the failed assistant message as `ChatMessage.errorCode`, which a host reads and the transcript never sends back.
12
+
7
13
  - e3de9ef: Tighter defaults for the web client and the in-page agent. Every changed default below names the option that restores the old behaviour.
8
14
 
9
15
  - **Write tools confirm by default.** An `st.tool` whose name starts with `remove`, `delete`, `create`, `update`, `upsert`, `submit`, `save`, `send` or `export` now shows the approval card unless it declares `confirm`. Before, only `remove*` did. This covers `submit<Model>` in `Model.EditModal` and `exportCsvOf<Model>` / `exportJsonOf<Model>` in `Data.ListContainer`. Opt out per tool with `{ confirm: false }`, which also drops the tool's confirm mark in the dock and the screen actions and its MCP `destructiveHint`, or app-wide with `AgentConfirm.set({ byName: (name) => name.startsWith("remove") })`.
@@ -95,7 +95,8 @@ export class Compaction {
95
95
  }
96
96
 
97
97
  static #charsOf(message: ChatMessage): number {
98
- const posted = message.usage ? { ...message, usage: undefined } : message;
98
+ const posted =
99
+ message.usage || message.errorCode ? { ...message, usage: undefined, errorCode: undefined } : message;
99
100
  const own = Compaction.#blanked(message.attachments);
100
101
  let images = own.images;
101
102
  const toolResults = message.toolResults?.map((result) => {