@inflatable-cookie/longhorn 0.2.0 → 0.2.2

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.
package/README.md CHANGED
@@ -15,7 +15,7 @@ Every domain is a subpath. `@inflatable-cookie/longhorn` itself resolves to
15
15
  | Subpath | Domain |
16
16
  | --- | --- |
17
17
  | `/core` | identity, opaque values, transports, diagnostics |
18
- | `/agent-control` | in-page semantic shim (contract 022 control surface). Synthetic events are untrusted (`isTrusted` stays false); `wait_for` is DOM-relative. |
18
+ | `/agent-control` | in-page semantic shim (contract 022 control surface). Synthetic events are untrusted (`isTrusted` stays false); `wait_for` is DOM-relative. `bindFileSelection` is the plugin-dialog replacement at picker call sites. |
19
19
  | `/config` | configuration store, backup, restore, recovery |
20
20
  | `/layout` | containers, regions, panels, sizing |
21
21
  | `/surfaces`, `/surface-transfer` | optional Surface documents and their transfer |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inflatable-cookie/longhorn",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -10,6 +10,7 @@ export {
10
10
  TRUNCATED_ROLE,
11
11
  installAgentControlShim,
12
12
  type AgentControlApi,
13
+ type FileInputFile,
13
14
  type PageEvent,
14
15
  type PageState,
15
16
  type SemanticNode,
@@ -18,3 +19,20 @@ export {
18
19
  type ToolErrorBody,
19
20
  type WaitPredicate,
20
21
  } from "./shim.ts";
22
+ export {
23
+ BEGIN_SELECTION_COMMAND,
24
+ SELECTION_ORIGIN_AGENT,
25
+ SELECTION_ORIGIN_HUMAN,
26
+ SELECTION_RESOURCE_URI,
27
+ bindFileSelection,
28
+ currentSelectionOrigin,
29
+ type DialogFilter,
30
+ type FileSelectionApi,
31
+ type FileSelectionPorts,
32
+ type FileSelectionWorld,
33
+ type OpenDialogOptions,
34
+ type OpenDialogResult,
35
+ type SaveDialogOptions,
36
+ type SaveDialogResult,
37
+ type SelectionOrigin,
38
+ } from "./selection.ts";
@@ -0,0 +1,113 @@
1
+ //! Consumer call-site replacement for plugin-dialog `open`/`save`.
2
+ //!
3
+ //! Agent-originated calls publish a pending selection before any OS panel
4
+ //! opens. Human-originated calls pass the original options to the plugin
5
+ //! unchanged. Origin is the in-page shim, not an active-server flag.
6
+
7
+ import { SHIM_GLOBAL, type AgentControlApi } from "./shim.ts";
8
+
9
+ /** Renderer invoke name. Host-protocol pairs this with the Rust command. */
10
+ export const BEGIN_SELECTION_COMMAND = "longhorn_agent_control_begin_selection";
11
+
12
+ /** Pending-selection MCP resource. */
13
+ export const SELECTION_RESOURCE_URI = "longhorn://agent-control/selection";
14
+
15
+ /** Wire token for agent origin. Matches the Rust `SELECTION_ORIGIN_AGENT`. */
16
+ export const SELECTION_ORIGIN_AGENT = "agent";
17
+
18
+ /** Wire token for human origin. Matches the Rust `SELECTION_ORIGIN_HUMAN`. */
19
+ export const SELECTION_ORIGIN_HUMAN = "human";
20
+
21
+ /** Serializable origin a consumer passes into its own command arguments. */
22
+ export type SelectionOrigin = typeof SELECTION_ORIGIN_AGENT | typeof SELECTION_ORIGIN_HUMAN;
23
+
24
+ export type DialogFilter = {
25
+ name: string;
26
+ extensions: string[];
27
+ };
28
+
29
+ export type OpenDialogOptions = {
30
+ title?: string;
31
+ defaultPath?: string;
32
+ filters?: DialogFilter[];
33
+ multiple?: boolean;
34
+ directory?: boolean;
35
+ };
36
+
37
+ export type SaveDialogOptions = {
38
+ title?: string;
39
+ defaultPath?: string;
40
+ filters?: DialogFilter[];
41
+ };
42
+
43
+ export type OpenDialogResult = string | string[] | null;
44
+ export type SaveDialogResult = string | null;
45
+
46
+ export type FileSelectionPorts = {
47
+ invoke: (command: string, args: Record<string, unknown>) => Promise<unknown>;
48
+ pluginOpen: (options?: OpenDialogOptions) => Promise<OpenDialogResult>;
49
+ pluginSave: (options?: SaveDialogOptions) => Promise<SaveDialogResult>;
50
+ };
51
+
52
+ export type FileSelectionWorld = {
53
+ readonly [SHIM_GLOBAL]?: Pick<AgentControlApi, "isAgentOriginated">;
54
+ };
55
+
56
+ export type FileSelectionApi = {
57
+ open: (options?: OpenDialogOptions) => Promise<OpenDialogResult>;
58
+ save: (options?: SaveDialogOptions) => Promise<SaveDialogResult>;
59
+ };
60
+
61
+ function isAgentOriginated(world: FileSelectionWorld): boolean {
62
+ return world[SHIM_GLOBAL]?.isAgentOriginated?.() === true;
63
+ }
64
+
65
+ /**
66
+ * Page origin as a command-argument token. Reads the installed shim;
67
+ * with no shim, or when the shim reports human, the token is `"human"`.
68
+ */
69
+ export function currentSelectionOrigin(world: object = globalThis): SelectionOrigin {
70
+ return isAgentOriginated(world as FileSelectionWorld)
71
+ ? SELECTION_ORIGIN_AGENT
72
+ : SELECTION_ORIGIN_HUMAN;
73
+ }
74
+
75
+ function beginOptions(
76
+ kind: "open" | "save",
77
+ options: OpenDialogOptions | SaveDialogOptions | undefined,
78
+ ): Record<string, unknown> {
79
+ const open = kind === "open" ? (options as OpenDialogOptions | undefined) : undefined;
80
+ return {
81
+ kind,
82
+ directory: open?.directory ?? false,
83
+ multiple: open?.multiple ?? false,
84
+ filters: options?.filters ?? [],
85
+ title: options?.title,
86
+ defaultPath: options?.defaultPath,
87
+ };
88
+ }
89
+
90
+ /**
91
+ * Binds plugin-compatible `open`/`save`. Call at consumer picker sites;
92
+ * do not monkey-patch plugin-dialog.
93
+ */
94
+ export function bindFileSelection(
95
+ ports: FileSelectionPorts,
96
+ world: object = globalThis,
97
+ ): FileSelectionApi {
98
+ const originWorld = world as FileSelectionWorld;
99
+ return {
100
+ open: async (options?: OpenDialogOptions) => {
101
+ if (!isAgentOriginated(originWorld)) return ports.pluginOpen(options);
102
+ return (await ports.invoke(BEGIN_SELECTION_COMMAND, {
103
+ options: beginOptions("open", options),
104
+ })) as OpenDialogResult;
105
+ },
106
+ save: async (options?: SaveDialogOptions) => {
107
+ if (!isAgentOriginated(originWorld)) return ports.pluginSave(options);
108
+ return (await ports.invoke(BEGIN_SELECTION_COMMAND, {
109
+ options: beginOptions("save", options),
110
+ })) as SaveDialogResult;
111
+ },
112
+ };
113
+ }
@@ -82,6 +82,12 @@ export type WaitPredicate =
82
82
  | { predicate: "pageUrlContains"; needle: string }
83
83
  | { predicate: "pageTitleContains"; needle: string };
84
84
 
85
+ export type FileInputFile = {
86
+ name: string;
87
+ mediaType?: string;
88
+ contentBase64: string;
89
+ };
90
+
85
91
  export type AgentControlApi = {
86
92
  snapshot: () => ShimResult<{ page: PageState; root: SemanticNode }>;
87
93
  click: (element: string) => ShimResult<Record<string, never>>;
@@ -97,7 +103,10 @@ export type AgentControlApi = {
97
103
  element?: string | null,
98
104
  ) => ShimResult<Record<string, never>>;
99
105
  drag: (source: string, target: string) => ShimResult<Record<string, never>>;
106
+ setFileInput: (element: string, files: FileInputFile[]) => ShimResult<Record<string, never>>;
100
107
  waitFor: (predicate: WaitPredicate) => ShimResult<{ holds: boolean }>;
108
+ markAgentOrigin: () => void;
109
+ isAgentOriginated: () => boolean;
101
110
  readEvents: (sinceSeq?: number) => {
102
111
  events: PageEvent[];
103
112
  nextSeq: number;
@@ -114,7 +123,13 @@ export type ShimWorld = {
114
123
  KeyboardEvent: typeof KeyboardEvent;
115
124
  Event: typeof Event;
116
125
  InputEvent?: typeof InputEvent;
117
- addEventListener: (type: string, listener: (event: Event) => void) => void;
126
+ File?: typeof File;
127
+ DataTransfer?: typeof DataTransfer;
128
+ addEventListener: (
129
+ type: string,
130
+ listener: (event: Event) => void,
131
+ options?: boolean | { capture?: boolean },
132
+ ) => void;
118
133
  onunhandledrejection?: ((event: Event) => void) | null;
119
134
  } & Record<string, unknown>;
120
135
 
@@ -124,6 +139,10 @@ function unresolved(element: string): ShimResult<never> {
124
139
  return { ok: false, error: { error: "unresolvedRef", element } };
125
140
  }
126
141
 
142
+ function unsupported(message: string): ShimResult<never> {
143
+ return { ok: false, error: { error: "unsupported", message } };
144
+ }
145
+
127
146
  function ok(): ActionOk {
128
147
  return { ok: true } as ActionOk;
129
148
  }
@@ -609,6 +628,87 @@ function drag(
609
628
  return ok();
610
629
  }
611
630
 
631
+ function decodeBase64(content: string): Uint8Array<ArrayBuffer> | null {
632
+ try {
633
+ const binary = atob(content);
634
+ const bytes = new Uint8Array(binary.length);
635
+ for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);
636
+ return bytes;
637
+ } catch {
638
+ return null;
639
+ }
640
+ }
641
+
642
+ function acceptMatches(fileName: string, mediaType: string, accept: string): boolean {
643
+ const tokens = accept
644
+ .split(",")
645
+ .map((token) => token.trim())
646
+ .filter((token) => token.length > 0);
647
+ if (tokens.length === 0) return true;
648
+ const name = fileName.toLowerCase();
649
+ const type = mediaType.toLowerCase();
650
+ return tokens.some((token) => {
651
+ const needle = token.toLowerCase();
652
+ if (needle.startsWith(".")) return name.endsWith(needle);
653
+ if (needle.endsWith("/*")) return type.startsWith(needle.slice(0, -1));
654
+ return type === needle;
655
+ });
656
+ }
657
+
658
+ function setFileInput(
659
+ world: ShimWorld,
660
+ element: string,
661
+ files: FileInputFile[],
662
+ ): ShimResult<Record<string, never>> {
663
+ const node = resolveRef(world.document, element);
664
+ if (!node) return unresolved(element);
665
+ const inputType = (prop<string>(node, "type") ?? node.getAttribute("type") ?? "").toLowerCase();
666
+ if (node.tagName !== "INPUT" || inputType !== "file") {
667
+ return unsupported("set_file_input requires an input type=file");
668
+ }
669
+ if (!Array.isArray(files) || files.length === 0) {
670
+ return unsupported("set_file_input requires at least one file");
671
+ }
672
+ const multiple = prop<boolean>(node, "multiple") === true || node.hasAttribute("multiple");
673
+ if (files.length > 1 && !multiple) {
674
+ return unsupported("set_file_input received multiple files for an input without multiple");
675
+ }
676
+ const FileCtor = world.File ?? (typeof File === "function" ? File : undefined);
677
+ const DataTransferCtor =
678
+ world.DataTransfer ?? (typeof DataTransfer === "function" ? DataTransfer : undefined);
679
+ if (!FileCtor || !DataTransferCtor) {
680
+ return unsupported("set_file_input needs File and DataTransfer in the page");
681
+ }
682
+ const accept = node.getAttribute("accept") ?? "";
683
+ const transfer = new DataTransferCtor();
684
+ for (const file of files) {
685
+ if (!file.name) return unsupported("set_file_input file name must be non-empty");
686
+ const bytes = decodeBase64(file.contentBase64);
687
+ if (!bytes) {
688
+ return unsupported(`set_file_input file ${JSON.stringify(file.name)} is not valid base64`);
689
+ }
690
+ const mediaType = file.mediaType ?? "";
691
+ if (!acceptMatches(file.name, mediaType, accept)) {
692
+ return unsupported(`set_file_input file ${JSON.stringify(file.name)} does not match accept`);
693
+ }
694
+ transfer.items.add(new FileCtor([bytes], file.name, mediaType ? { type: mediaType } : undefined));
695
+ }
696
+ try {
697
+ (node as HTMLInputElement).files = transfer.files;
698
+ } catch (error) {
699
+ return unsupported(
700
+ `the page refused FileList assignment from a constructed DataTransfer: ${String(error)}`,
701
+ );
702
+ }
703
+ const assigned = prop<ArrayLike<unknown>>(node, "files");
704
+ if (!assigned || assigned.length !== files.length) {
705
+ return unsupported("the page refused FileList assignment from a constructed DataTransfer");
706
+ }
707
+ node.dispatchEvent(new world.Event("input", { bubbles: true }));
708
+ node.dispatchEvent(new world.Event("change", { bubbles: true }));
709
+ return ok();
710
+ }
711
+
612
712
  function waitFor(world: ShimWorld, predicate: WaitPredicate): ShimResult<{ holds: boolean }> {
613
713
  switch (predicate.predicate) {
614
714
  case "refResolve":
@@ -703,18 +803,60 @@ function installEventRing(world: ShimWorld): AgentControlApi["readEvents"] {
703
803
  });
704
804
  }
705
805
 
806
+ function installOriginTracking(world: ShimWorld): Pick<
807
+ AgentControlApi,
808
+ "markAgentOrigin" | "isAgentOriginated"
809
+ > {
810
+ let agentOriginSeq = 0;
811
+ let humanOriginSeq = 0;
812
+ const markHuman = (event: Event) => {
813
+ if (event.isTrusted) humanOriginSeq = agentOriginSeq + 1;
814
+ };
815
+ world.addEventListener("pointerdown", markHuman, true);
816
+ world.addEventListener("keydown", markHuman, true);
817
+ world.addEventListener("click", markHuman, true);
818
+ return {
819
+ markAgentOrigin: () => {
820
+ agentOriginSeq = humanOriginSeq + 1;
821
+ },
822
+ isAgentOriginated: () => agentOriginSeq > humanOriginSeq,
823
+ };
824
+ }
825
+
706
826
  export function installAgentControlShim(world: ShimWorld): AgentControlApi {
707
827
  const existing = world[SHIM_GLOBAL] as AgentControlApi | undefined;
708
828
  if (existing) return existing;
709
829
  const readEvents = installEventRing(world);
830
+ const origin = installOriginTracking(world);
710
831
  const api: AgentControlApi = {
711
832
  snapshot: () => snapshot(world),
712
- click: (element) => click(world, element),
713
- type: (element, text) => typeInto(world, element, text),
714
- press: (key, modifiers, element) => press(world, key, modifiers, element),
715
- scroll: (deltaX, deltaY, element) => scroll(world, deltaX, deltaY, element),
716
- drag: (source, target) => drag(world, source, target),
833
+ click: (element) => {
834
+ origin.markAgentOrigin();
835
+ return click(world, element);
836
+ },
837
+ type: (element, text) => {
838
+ origin.markAgentOrigin();
839
+ return typeInto(world, element, text);
840
+ },
841
+ press: (key, modifiers, element) => {
842
+ origin.markAgentOrigin();
843
+ return press(world, key, modifiers, element);
844
+ },
845
+ scroll: (deltaX, deltaY, element) => {
846
+ origin.markAgentOrigin();
847
+ return scroll(world, deltaX, deltaY, element);
848
+ },
849
+ drag: (source, target) => {
850
+ origin.markAgentOrigin();
851
+ return drag(world, source, target);
852
+ },
853
+ setFileInput: (element, files) => {
854
+ origin.markAgentOrigin();
855
+ return setFileInput(world, element, files);
856
+ },
717
857
  waitFor: (predicate) => waitFor(world, predicate),
858
+ markAgentOrigin: origin.markAgentOrigin,
859
+ isAgentOriginated: origin.isAgentOriginated,
718
860
  readEvents,
719
861
  };
720
862
  world[SHIM_GLOBAL] = api;