@wenathlan/extension 1.1.11

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.
@@ -0,0 +1,297 @@
1
+ // memory.ts
2
+ var sessionmemory = class {
3
+ constructor(adapter) {
4
+ this.adapter = adapter;
5
+ }
6
+ async getconfig() {
7
+ return this.adapter.get("config");
8
+ }
9
+ async setconfig(value) {
10
+ return this.adapter.set("config", value);
11
+ }
12
+ async getsession() {
13
+ return this.adapter.get("session");
14
+ }
15
+ async setsession(value) {
16
+ return this.adapter.set("session", value);
17
+ }
18
+ async getplan() {
19
+ return this.adapter.get("plan");
20
+ }
21
+ async setplan(value) {
22
+ return this.adapter.set("plan", value);
23
+ }
24
+ async getdiagnostic() {
25
+ return this.adapter.get("diagnostic");
26
+ }
27
+ async setdiagnostic(value) {
28
+ return this.adapter.set("diagnostic", value);
29
+ }
30
+ async getaudit() {
31
+ return await this.adapter.get("audit") ?? [];
32
+ }
33
+ async addaudi(event) {
34
+ const records = await this.getaudit();
35
+ await this.adapter.set("audit", [event, ...records].slice(0, 100));
36
+ }
37
+ };
38
+ function randomid() {
39
+ return crypto.randomUUID();
40
+ }
41
+
42
+ // policy.ts
43
+ var sensitiveactions = /* @__PURE__ */ new Set(["click", "type", "navigate"]);
44
+ var allowedactions = /* @__PURE__ */ new Set(["observe", "inspect", "focus", "click", "type", "navigate"]);
45
+ function normalizeendpoint(value) {
46
+ const endpoint = new URL(value.trim());
47
+ if (endpoint.protocol !== "https:") throw new Error("Devthink accepts HTTPS endpoints only.");
48
+ if (endpoint.username || endpoint.password) throw new Error("Endpoint credentials are not allowed in the URL.");
49
+ return { endpoint: endpoint.toString(), origin: endpoint.origin, configuredat: Date.now() };
50
+ }
51
+ function hostpattern(origin) {
52
+ const parsed = new URL(origin);
53
+ if (parsed.protocol !== "https:") throw new Error("Only HTTPS origins can be granted.");
54
+ return `${parsed.origin}/*`;
55
+ }
56
+ function actionrisk(kind) {
57
+ if (!allowedactions.has(kind)) throw new Error("Unsupported browser action.");
58
+ if (sensitiveactions.has(kind)) return "sensitive";
59
+ return kind === "focus" ? "interaction" : "read";
60
+ }
61
+ function validatestep(step, origin) {
62
+ if (!allowedactions.has(step.kind)) return { allowed: false, reason: "Unsupported action kind." };
63
+ if (!step.summary.trim()) return { allowed: false, reason: "A human-readable action summary is required." };
64
+ if ((step.kind === "click" || step.kind === "focus" || step.kind === "inspect" || step.kind === "type") && !step.target?.trim()) return { allowed: false, reason: "A page target is required." };
65
+ if (step.kind === "navigate") {
66
+ if (!step.value) return { allowed: false, reason: "A navigation URL is required." };
67
+ try {
68
+ if (new URL(step.value).origin !== origin) return { allowed: false, reason: "Navigation must remain within the approved origin." };
69
+ } catch {
70
+ return { allowed: false, reason: "Navigation URL is invalid." };
71
+ }
72
+ }
73
+ return { allowed: true };
74
+ }
75
+ function canexecute(input) {
76
+ const now = input.now ?? Date.now();
77
+ if (!input.session || input.session.stoppedat) return { allowed: false, reason: "No active browser session exists." };
78
+ if (input.session.expiresat <= now) return { allowed: false, reason: "The browser session has expired." };
79
+ if (input.session.tabid !== input.tabid || input.session.origin !== input.origin) return { allowed: false, reason: "The action is outside the approved tab or origin." };
80
+ if (!input.plan || input.plan.state !== "approved") return { allowed: false, reason: "The plan has not received explicit approval." };
81
+ if (input.plan.expiresat <= now) return { allowed: false, reason: "The approved plan has expired." };
82
+ return validatestep(input.step, input.origin);
83
+ }
84
+
85
+ // version.ts
86
+ var packageversion = "1.1.11";
87
+
88
+ // types.ts
89
+ var protocolversion = packageversion;
90
+
91
+ // protocol.ts
92
+ function record(value) {
93
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Protocol message must be an object.");
94
+ return value;
95
+ }
96
+ function text(value, field) {
97
+ if (typeof value !== "string" || !value.trim()) throw new Error(`${field} must be a non-empty string.`);
98
+ return value.trim();
99
+ }
100
+ function parseproposal(value, origin) {
101
+ const root = record(value);
102
+ if (root.version !== protocolversion) throw new Error("Unsupported protocol version.");
103
+ const planinput = record(root.plan);
104
+ const stepsinput = planinput.steps;
105
+ if (!Array.isArray(stepsinput) || stepsinput.length === 0 || stepsinput.length > 20) throw new Error("A plan needs between one and twenty steps.");
106
+ const steps = stepsinput.map((input, index) => {
107
+ const candidate = record(input);
108
+ const kind = text(candidate.kind, `step ${index + 1} kind`);
109
+ const step = {
110
+ id: typeof candidate.id === "string" ? candidate.id : crypto.randomUUID(),
111
+ kind,
112
+ summary: text(candidate.summary, `step ${index + 1} summary`),
113
+ risk: actionrisk(kind),
114
+ ...typeof candidate.target === "string" ? { target: candidate.target } : {},
115
+ ...typeof candidate.value === "string" ? { value: candidate.value } : {}
116
+ };
117
+ const evaluation = validatestep(step, origin);
118
+ if (!evaluation.allowed) throw new Error(evaluation.reason);
119
+ return step;
120
+ });
121
+ const createdat = Date.now();
122
+ const plan = {
123
+ id: typeof planinput.id === "string" ? planinput.id : crypto.randomUUID(),
124
+ objective: text(planinput.objective, "objective"),
125
+ origin,
126
+ steps,
127
+ createdat,
128
+ expiresat: Math.min(typeof planinput.expiresat === "number" ? planinput.expiresat : createdat + 10 * 60 * 1e3, createdat + 30 * 60 * 1e3),
129
+ state: "pending"
130
+ };
131
+ if (plan.expiresat <= createdat) throw new Error("Plan expiry must be in the future.");
132
+ return { version: protocolversion, plan };
133
+ }
134
+ function requestbody(input) {
135
+ return JSON.stringify({ version: protocolversion, objective: input.objective, session: input.session, observation: input.observation });
136
+ }
137
+
138
+ // extension/background.ts
139
+ var sessionduration = 15 * 60 * 1e3;
140
+ var chromestorage = {
141
+ async get(key) {
142
+ return (await chrome.storage.local.get(key))[key];
143
+ },
144
+ async set(key, value) {
145
+ await chrome.storage.local.set({ [key]: value });
146
+ }
147
+ };
148
+ var memory = new sessionmemory(chromestorage);
149
+ function extensionpage(sender) {
150
+ return sender.id === chrome.runtime.id && Boolean(sender.url?.startsWith(chrome.runtime.getURL("")));
151
+ }
152
+ async function audit(kind, summary, extra = {}) {
153
+ await memory.addaudi({ id: randomid(), kind, at: Date.now(), summary, ...extra });
154
+ }
155
+ async function activecontext() {
156
+ const [tab] = await chrome.tabs.query({ active: true, lastFocusedWindow: true });
157
+ if (!tab?.id || !tab.url) throw new Error("No active web tab is available.");
158
+ const origin = new URL(tab.url).origin;
159
+ if (!origin.startsWith("https://")) throw new Error("Devthink can work with HTTPS pages only.");
160
+ return { tab, origin };
161
+ }
162
+ async function snapshot(tabid) {
163
+ await chrome.scripting.executeScript({ target: { tabId: tabid }, files: ["pagebridge.js"] });
164
+ const result = await chrome.scripting.executeScript({ target: { tabId: tabid }, func: () => {
165
+ const bridge = globalThis.devthinkbridge;
166
+ if (!bridge) throw new Error("Devthink page bridge is unavailable.");
167
+ return bridge.capturesnapshot();
168
+ } });
169
+ const value = result[0]?.result;
170
+ if (!value) throw new Error("The page did not return an observation.");
171
+ return value;
172
+ }
173
+ async function startsession() {
174
+ const { tab, origin } = await activecontext();
175
+ const session = { id: randomid(), tabid: tab.id, origin, startedat: Date.now(), expiresat: Date.now() + sessionduration };
176
+ await memory.setsession(session);
177
+ await audit("session", `Session started for ${origin}.`, { sessionid: session.id });
178
+ return session;
179
+ }
180
+ async function diagnostic() {
181
+ const session = await memory.getsession();
182
+ const { tab, origin } = await activecontext();
183
+ if (!session || session.stoppedat || session.expiresat <= Date.now() || session.tabid !== tab.id || session.origin !== origin) throw new Error("Start a current session for this active tab before diagnostics.");
184
+ const observation = await snapshot(session.tabid);
185
+ const report = { id: randomid(), sessionid: session.id, origin, capturedat: Date.now(), tabid: session.tabid, title: observation.title, textlength: observation.textlength, interactivecount: observation.interactive.length, formcount: observation.forms.length, bridgeavailable: true };
186
+ await memory.setdiagnostic(report);
187
+ await audit("observe", "Structured diagnostics captured for the approved active tab.", { sessionid: session.id });
188
+ return report;
189
+ }
190
+ function localplan(objective, session) {
191
+ const now = Date.now();
192
+ return { id: randomid(), objective, origin: session.origin, steps: [{ id: randomid(), kind: "observe", summary: "Capture a bounded semantic snapshot of the approved active tab.", risk: "read" }], createdat: now, expiresat: now + sessionduration, state: "pending" };
193
+ }
194
+ async function propose(objective, remote) {
195
+ if (!objective.trim()) throw new Error("An objective is required.");
196
+ const session = await memory.getsession();
197
+ if (!session || session.stoppedat || session.expiresat <= Date.now()) throw new Error("Start a current browser session before requesting a plan.");
198
+ const { tab, origin } = await activecontext();
199
+ if (session.tabid !== tab.id || session.origin !== origin) throw new Error("The selected tab or origin no longer matches the approved session.");
200
+ const observation = await snapshot(session.tabid);
201
+ const config = await memory.getconfig();
202
+ let plan = localplan(objective.trim(), session);
203
+ if (remote) {
204
+ if (!config) throw new Error("Configure an approved HTTPS endpoint before requesting a remote proposal.");
205
+ const response = await fetch(config.endpoint, { method: "POST", headers: { "content-type": "application/json" }, credentials: "omit", body: requestbody({ objective: objective.trim(), session, observation }) });
206
+ if (!response.ok) throw new Error(`Proposal endpoint returned ${response.status}.`);
207
+ plan = parseproposal(await response.json(), session.origin).plan;
208
+ }
209
+ await memory.setplan(plan);
210
+ await audit("proposal", `Plan proposed with ${plan.steps.length} reviewed step${plan.steps.length === 1 ? "" : "s"}.`, { sessionid: session.id, planid: plan.id });
211
+ return plan;
212
+ }
213
+ async function executestep(stepid) {
214
+ const session = await memory.getsession();
215
+ const plan = await memory.getplan();
216
+ const { tab, origin } = await activecontext();
217
+ const step = plan?.steps.find((candidate) => candidate.id === stepid);
218
+ if (!step) throw new Error("Reviewed step was not found.");
219
+ const gate = canexecute({ session, plan, step, tabid: tab.id, origin });
220
+ if (!gate.allowed) throw new Error(gate.reason);
221
+ const fresh = await snapshot(tab.id);
222
+ if (step.target && !fresh.interactive.some((item) => item.selector === step.target)) throw new Error("The page changed and the target must be reviewed again.");
223
+ const result = await chrome.scripting.executeScript({ target: { tabId: tab.id }, func: (action, expectedorigin) => {
224
+ const bridge = globalThis.devthinkbridge;
225
+ if (!bridge) throw new Error("Devthink page bridge is unavailable.");
226
+ return bridge.performstep(action, expectedorigin);
227
+ }, args: [step, origin] });
228
+ const output = result[0]?.result;
229
+ const summary = output?.summary ?? "The page action returned no result.";
230
+ await audit(output?.ok ? "action" : "error", summary, { ...session ? { sessionid: session.id } : {}, ...plan ? { planid: plan.id } : {}, stepid });
231
+ return output ?? { ok: false, summary };
232
+ }
233
+ async function handlerequest(message, sender) {
234
+ if (!extensionpage(sender)) throw new Error("Requests are accepted only from Devthink extension pages.");
235
+ const input = message;
236
+ switch (input.kind) {
237
+ case "configure": {
238
+ const config = normalizeendpoint(input.endpoint ?? "");
239
+ const granted = await chrome.permissions.contains({ origins: [hostpattern(config.origin)] });
240
+ if (!granted) throw new Error("The endpoint origin has not received optional permission.");
241
+ await memory.setconfig(config);
242
+ await audit("configure", `Configured user-selected endpoint ${config.origin}.`);
243
+ return config;
244
+ }
245
+ case "startsession":
246
+ return startsession();
247
+ case "context":
248
+ return { config: await memory.getconfig(), session: await memory.getsession(), plan: await memory.getplan(), diagnostic: await memory.getdiagnostic(), audit: await memory.getaudit() };
249
+ case "diagnostic":
250
+ return diagnostic();
251
+ case "proposelocal":
252
+ return propose(input.objective ?? "", false);
253
+ case "proposeremote":
254
+ return propose(input.objective ?? "", true);
255
+ case "approve": {
256
+ const plan = await memory.getplan();
257
+ if (!plan || plan.state !== "pending") throw new Error("Only a pending plan can be approved.");
258
+ const approved = { ...plan, state: "approved", approvedat: Date.now() };
259
+ await memory.setplan(approved);
260
+ const current = await memory.getsession();
261
+ await audit("approval", "The user approved the reviewed plan.", { ...current ? { sessionid: current.id } : {}, planid: approved.id });
262
+ return approved;
263
+ }
264
+ case "reject": {
265
+ const plan = await memory.getplan();
266
+ if (!plan) throw new Error("No plan is available to reject.");
267
+ const rejected = { ...plan, state: "rejected" };
268
+ await memory.setplan(rejected);
269
+ const current = await memory.getsession();
270
+ await audit("approval", "The user rejected the plan.", { ...current ? { sessionid: current.id } : {}, planid: rejected.id });
271
+ return rejected;
272
+ }
273
+ case "execute":
274
+ return executestep(input.stepid ?? "");
275
+ case "stop": {
276
+ const session = await memory.getsession();
277
+ if (session) await memory.setsession({ ...session, stoppedat: Date.now() });
278
+ const plan = await memory.getplan();
279
+ if (plan && ["pending", "approved"].includes(plan.state)) await memory.setplan({ ...plan, state: "cancelled" });
280
+ await audit("stop", "The user stopped the browser session.", { ...session ? { sessionid: session.id } : {}, ...plan ? { planid: plan.id } : {} });
281
+ return { stopped: true };
282
+ }
283
+ default:
284
+ throw new Error("Unknown Devthink request.");
285
+ }
286
+ }
287
+ chrome.runtime.onMessage.addListener((message, sender, sendresponse) => {
288
+ handlerequest(message, sender).then((value) => sendresponse({ ok: true, value })).catch((error) => sendresponse({ ok: false, error: error instanceof Error ? error.message : String(error) }));
289
+ return true;
290
+ });
291
+ chrome.runtime.onConnect.addListener((port) => {
292
+ if (port.name !== "devthinksidepanel" || port.sender?.id !== chrome.runtime.id || !port.sender.url?.startsWith(chrome.runtime.getURL(""))) return port.disconnect();
293
+ port.onMessage.addListener((message) => {
294
+ handlerequest(message, port.sender ?? {}).then((value) => port.postMessage({ ok: true, value })).catch((error) => port.postMessage({ ok: false, error: error instanceof Error ? error.message : String(error) }));
295
+ });
296
+ });
297
+ //# sourceMappingURL=background.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../memory.ts", "../../policy.ts", "../../version.ts", "../../types.ts", "../../protocol.ts", "../background.ts"],
4
+ "sourcesContent": ["import type { agentplan, agentsession, auditevent, diagnosticreport, endpointconfig } from \"./types.js\";\n\n/** Provides a small storage seam that works in browser, tests and future adapters. */\nexport interface memoryadapter {\n get<T>(key: string): Promise<T | undefined>;\n set<T>(key: string, value: T): Promise<void>;\n}\n\nexport class sessionmemory {\n constructor(private readonly adapter: memoryadapter) {}\n\n async getconfig(): Promise<endpointconfig | undefined> { return this.adapter.get<endpointconfig>(\"config\"); }\n async setconfig(value: endpointconfig): Promise<void> { return this.adapter.set(\"config\", value); }\n async getsession(): Promise<agentsession | undefined> { return this.adapter.get<agentsession>(\"session\"); }\n async setsession(value: agentsession): Promise<void> { return this.adapter.set(\"session\", value); }\n async getplan(): Promise<agentplan | undefined> { return this.adapter.get<agentplan>(\"plan\"); }\n async setplan(value: agentplan): Promise<void> { return this.adapter.set(\"plan\", value); }\n async getdiagnostic(): Promise<diagnosticreport | undefined> { return this.adapter.get<diagnosticreport>(\"diagnostic\"); }\n async setdiagnostic(value: diagnosticreport): Promise<void> { return this.adapter.set(\"diagnostic\", value); }\n async getaudit(): Promise<auditevent[]> { return (await this.adapter.get<auditevent[]>(\"audit\")) ?? []; }\n async addaudi(event: auditevent): Promise<void> {\n const records = await this.getaudit();\n await this.adapter.set(\"audit\", [event, ...records].slice(0, 100));\n }\n}\n\n/** Creates identifiers locally without a network dependency. */\nexport function randomid(): string {\n return crypto.randomUUID();\n}\n", "import type { actionkind, agentplan, agentsession, endpointconfig, policyevaluation, toolstep } from \"./types.js\";\n\nconst sensitiveactions = new Set<actionkind>([\"click\", \"type\", \"navigate\"]);\nconst allowedactions = new Set<actionkind>([\"observe\", \"inspect\", \"focus\", \"click\", \"type\", \"navigate\"]);\n\n/** Normalizes a user supplied HTTPS endpoint without preserving a provider lock-in. */\nexport function normalizeendpoint(value: string): endpointconfig {\n const endpoint = new URL(value.trim());\n if (endpoint.protocol !== \"https:\") throw new Error(\"Devthink accepts HTTPS endpoints only.\");\n if (endpoint.username || endpoint.password) throw new Error(\"Endpoint credentials are not allowed in the URL.\");\n return { endpoint: endpoint.toString(), origin: endpoint.origin, configuredat: Date.now() };\n}\n\n/** Creates the exact optional host pattern requested from Chromium. */\nexport function hostpattern(origin: string): string {\n const parsed = new URL(origin);\n if (parsed.protocol !== \"https:\") throw new Error(\"Only HTTPS origins can be granted.\");\n return `${parsed.origin}/*`;\n}\n\n/** Defines action risk from a fixed local allowlist. */\nexport function actionrisk(kind: actionkind): \"read\" | \"interaction\" | \"sensitive\" {\n if (!allowedactions.has(kind)) throw new Error(\"Unsupported browser action.\");\n if (sensitiveactions.has(kind)) return \"sensitive\";\n return kind === \"focus\" ? \"interaction\" : \"read\";\n}\n\n/** Validates a single proposal against the active tab origin and local policy. */\nexport function validatestep(step: toolstep, origin: string): policyevaluation {\n if (!allowedactions.has(step.kind)) return { allowed: false, reason: \"Unsupported action kind.\" };\n if (!step.summary.trim()) return { allowed: false, reason: \"A human-readable action summary is required.\" };\n if ((step.kind === \"click\" || step.kind === \"focus\" || step.kind === \"inspect\" || step.kind === \"type\") && !step.target?.trim()) return { allowed: false, reason: \"A page target is required.\" };\n if (step.kind === \"navigate\") {\n if (!step.value) return { allowed: false, reason: \"A navigation URL is required.\" };\n try {\n if (new URL(step.value).origin !== origin) return { allowed: false, reason: \"Navigation must remain within the approved origin.\" };\n } catch {\n return { allowed: false, reason: \"Navigation URL is invalid.\" };\n }\n }\n return { allowed: true };\n}\n\n/** Applies the consent gate immediately before an action reaches the page bridge. */\nexport function canexecute(input: { session: agentsession | undefined; plan: agentplan | undefined; step: toolstep; tabid: number; origin: string; now?: number }): policyevaluation {\n const now = input.now ?? Date.now();\n if (!input.session || input.session.stoppedat) return { allowed: false, reason: \"No active browser session exists.\" };\n if (input.session.expiresat <= now) return { allowed: false, reason: \"The browser session has expired.\" };\n if (input.session.tabid !== input.tabid || input.session.origin !== input.origin) return { allowed: false, reason: \"The action is outside the approved tab or origin.\" };\n if (!input.plan || input.plan.state !== \"approved\") return { allowed: false, reason: \"The plan has not received explicit approval.\" };\n if (input.plan.expiresat <= now) return { allowed: false, reason: \"The approved plan has expired.\" };\n return validatestep(input.step, input.origin);\n}\n", "/** Canonical package version synchronized from package.json. */\nexport const packageversion = \"1.1.11\" as const;\n", "/** Shared contracts for every Devthink target. */\nimport { packageversion } from \"./version.js\";\n\nexport const protocolversion = packageversion;\n\nexport type actionkind = \"observe\" | \"inspect\" | \"focus\" | \"click\" | \"type\" | \"navigate\";\nexport type actionrisk = \"read\" | \"interaction\" | \"sensitive\";\nexport type planstate = \"draft\" | \"pending\" | \"approved\" | \"rejected\" | \"expired\" | \"completed\" | \"cancelled\";\nexport type auditkind = \"configure\" | \"session\" | \"observe\" | \"proposal\" | \"approval\" | \"action\" | \"error\" | \"stop\";\n\nexport interface toolstep {\n id: string;\n kind: actionkind;\n target?: string;\n value?: string;\n summary: string;\n risk: actionrisk;\n}\n\nexport interface agentplan {\n id: string;\n objective: string;\n origin: string;\n steps: toolstep[];\n createdat: number;\n expiresat: number;\n state: planstate;\n approvedat?: number;\n}\n\nexport interface agentsession {\n id: string;\n tabid: number;\n origin: string;\n startedat: number;\n expiresat: number;\n stoppedat?: number;\n}\n\nexport interface endpointconfig {\n endpoint: string;\n origin: string;\n configuredat: number;\n}\n\nexport interface observation {\n url: string;\n title: string;\n textpreview: string;\n textlength: number;\n forms: Array<{ label: string; type: string; name: string }>;\n interactive: Array<{ selector: string; role: string; label: string }>;\n capturedat: number;\n}\n\nexport interface auditevent {\n id: string;\n kind: auditkind;\n at: number;\n summary: string;\n sessionid?: string;\n planid?: string;\n stepid?: string;\n}\n\nexport interface diagnosticreport {\n id: string;\n sessionid: string;\n origin: string;\n capturedat: number;\n tabid: number;\n title: string;\n textlength: number;\n interactivecount: number;\n formcount: number;\n bridgeavailable: boolean;\n}\n\nexport interface proposalrequest {\n objective: string;\n session: agentsession;\n observation: observation;\n}\n\nexport interface planproposal {\n version: typeof protocolversion;\n plan: agentplan;\n}\n\nexport interface policyevaluation {\n allowed: boolean;\n reason?: string;\n}\n", "import { actionrisk, validatestep } from \"./policy.js\";\nimport { protocolversion, type agentplan, type planproposal, type proposalrequest, type toolstep } from \"./types.js\";\n\nfunction record(value: unknown): Record<string, unknown> {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) throw new Error(\"Protocol message must be an object.\");\n return value as Record<string, unknown>;\n}\n\nfunction text(value: unknown, field: string): string {\n if (typeof value !== \"string\" || !value.trim()) throw new Error(`${field} must be a non-empty string.`);\n return value.trim();\n}\n\n/** Validates agent output before it becomes a locally reviewable plan. */\nexport function parseproposal(value: unknown, origin: string): planproposal {\n const root = record(value);\n if (root.version !== protocolversion) throw new Error(\"Unsupported protocol version.\");\n const planinput = record(root.plan);\n const stepsinput = planinput.steps;\n if (!Array.isArray(stepsinput) || stepsinput.length === 0 || stepsinput.length > 20) throw new Error(\"A plan needs between one and twenty steps.\");\n const steps: toolstep[] = stepsinput.map((input, index) => {\n const candidate = record(input);\n const kind = text(candidate.kind, `step ${index + 1} kind`) as toolstep[\"kind\"];\n const step: toolstep = {\n id: typeof candidate.id === \"string\" ? candidate.id : crypto.randomUUID(),\n kind,\n summary: text(candidate.summary, `step ${index + 1} summary`),\n risk: actionrisk(kind),\n ...(typeof candidate.target === \"string\" ? { target: candidate.target } : {}),\n ...(typeof candidate.value === \"string\" ? { value: candidate.value } : {}),\n };\n const evaluation = validatestep(step, origin);\n if (!evaluation.allowed) throw new Error(evaluation.reason);\n return step;\n });\n const createdat = Date.now();\n const plan: agentplan = {\n id: typeof planinput.id === \"string\" ? planinput.id : crypto.randomUUID(),\n objective: text(planinput.objective, \"objective\"),\n origin,\n steps,\n createdat,\n expiresat: Math.min(typeof planinput.expiresat === \"number\" ? planinput.expiresat : createdat + 10 * 60 * 1000, createdat + 30 * 60 * 1000),\n state: \"pending\",\n };\n if (plan.expiresat <= createdat) throw new Error(\"Plan expiry must be in the future.\");\n return { version: protocolversion, plan };\n}\n\n/** Shapes the only data that may be sent to a user-configured agent endpoint. */\nexport function requestbody(input: proposalrequest): string {\n return JSON.stringify({ version: protocolversion, objective: input.objective, session: input.session, observation: input.observation });\n}\n", "import { randomid, sessionmemory } from \"../memory.js\";\nimport { canexecute, hostpattern, normalizeendpoint } from \"../policy.js\";\nimport { parseproposal, requestbody } from \"../protocol.js\";\nimport type { agentplan, agentsession, auditevent, diagnosticreport, observation, toolstep } from \"../types.js\";\n\nconst sessionduration = 15 * 60 * 1000;\n\nconst chromestorage = {\n async get<T>(key: string): Promise<T | undefined> { return (await chrome.storage.local.get(key))[key] as T | undefined; },\n async set<T>(key: string, value: T): Promise<void> { await chrome.storage.local.set({ [key]: value }); },\n};\nconst memory = new sessionmemory(chromestorage);\n\nfunction extensionpage(sender: chrome.runtime.MessageSender): boolean {\n return sender.id === chrome.runtime.id && Boolean(sender.url?.startsWith(chrome.runtime.getURL(\"\")));\n}\n\nasync function audit(kind: auditevent[\"kind\"], summary: string, extra: Partial<auditevent> = {}): Promise<void> {\n await memory.addaudi({ id: randomid(), kind, at: Date.now(), summary, ...extra });\n}\n\nasync function activecontext(): Promise<{ tab: chrome.tabs.Tab; origin: string }> {\n const [tab] = await chrome.tabs.query({ active: true, lastFocusedWindow: true });\n if (!tab?.id || !tab.url) throw new Error(\"No active web tab is available.\");\n const origin = new URL(tab.url).origin;\n if (!origin.startsWith(\"https://\")) throw new Error(\"Devthink can work with HTTPS pages only.\");\n return { tab, origin };\n}\n\nasync function snapshot(tabid: number): Promise<observation> {\n await chrome.scripting.executeScript({ target: { tabId: tabid }, files: [\"pagebridge.js\"] });\n const result = await chrome.scripting.executeScript({ target: { tabId: tabid }, func: () => {\n const bridge = (globalThis as typeof globalThis & { devthinkbridge?: { capturesnapshot: () => observation } }).devthinkbridge;\n if (!bridge) throw new Error(\"Devthink page bridge is unavailable.\");\n return bridge.capturesnapshot();\n } });\n const value = result[0]?.result;\n if (!value) throw new Error(\"The page did not return an observation.\");\n return value as observation;\n}\n\nasync function startsession(): Promise<agentsession> {\n const { tab, origin } = await activecontext();\n const session: agentsession = { id: randomid(), tabid: tab.id as number, origin, startedat: Date.now(), expiresat: Date.now() + sessionduration };\n await memory.setsession(session);\n await audit(\"session\", `Session started for ${origin}.`, { sessionid: session.id });\n return session;\n}\n\nasync function diagnostic(): Promise<diagnosticreport> {\n const session = await memory.getsession();\n const { tab, origin } = await activecontext();\n if (!session || session.stoppedat || session.expiresat <= Date.now() || session.tabid !== tab.id || session.origin !== origin) throw new Error(\"Start a current session for this active tab before diagnostics.\");\n const observation = await snapshot(session.tabid);\n const report: diagnosticreport = { id: randomid(), sessionid: session.id, origin, capturedat: Date.now(), tabid: session.tabid, title: observation.title, textlength: observation.textlength, interactivecount: observation.interactive.length, formcount: observation.forms.length, bridgeavailable: true };\n await memory.setdiagnostic(report);\n await audit(\"observe\", \"Structured diagnostics captured for the approved active tab.\", { sessionid: session.id });\n return report;\n}\n\nfunction localplan(objective: string, session: agentsession): agentplan {\n const now = Date.now();\n return { id: randomid(), objective, origin: session.origin, steps: [{ id: randomid(), kind: \"observe\", summary: \"Capture a bounded semantic snapshot of the approved active tab.\", risk: \"read\" }], createdat: now, expiresat: now + sessionduration, state: \"pending\" };\n}\n\nasync function propose(objective: string, remote: boolean): Promise<agentplan> {\n if (!objective.trim()) throw new Error(\"An objective is required.\");\n const session = await memory.getsession();\n if (!session || session.stoppedat || session.expiresat <= Date.now()) throw new Error(\"Start a current browser session before requesting a plan.\");\n const { tab, origin } = await activecontext();\n if (session.tabid !== tab.id || session.origin !== origin) throw new Error(\"The selected tab or origin no longer matches the approved session.\");\n const observation = await snapshot(session.tabid);\n const config = await memory.getconfig();\n let plan = localplan(objective.trim(), session);\n if (remote) {\n if (!config) throw new Error(\"Configure an approved HTTPS endpoint before requesting a remote proposal.\");\n const response = await fetch(config.endpoint, { method: \"POST\", headers: { \"content-type\": \"application/json\" }, credentials: \"omit\", body: requestbody({ objective: objective.trim(), session, observation }) });\n if (!response.ok) throw new Error(`Proposal endpoint returned ${response.status}.`);\n plan = parseproposal(await response.json(), session.origin).plan;\n }\n await memory.setplan(plan);\n await audit(\"proposal\", `Plan proposed with ${plan.steps.length} reviewed step${plan.steps.length === 1 ? \"\" : \"s\"}.`, { sessionid: session.id, planid: plan.id });\n return plan;\n}\n\nasync function executestep(stepid: string): Promise<{ ok: boolean; summary: string }> {\n const session = await memory.getsession();\n const plan = await memory.getplan();\n const { tab, origin } = await activecontext();\n const step = plan?.steps.find(candidate => candidate.id === stepid);\n if (!step) throw new Error(\"Reviewed step was not found.\");\n const gate = canexecute({ session, plan, step, tabid: tab.id as number, origin });\n if (!gate.allowed) throw new Error(gate.reason);\n const fresh = await snapshot(tab.id as number);\n if (step.target && !fresh.interactive.some(item => item.selector === step.target)) throw new Error(\"The page changed and the target must be reviewed again.\");\n const result = await chrome.scripting.executeScript({ target: { tabId: tab.id as number }, func: (action: toolstep, expectedorigin: string) => {\n const bridge = (globalThis as typeof globalThis & { devthinkbridge?: { performstep: (input: toolstep, origin: string) => { ok: boolean; summary: string } } }).devthinkbridge;\n if (!bridge) throw new Error(\"Devthink page bridge is unavailable.\");\n return bridge.performstep(action, expectedorigin);\n }, args: [step, origin] });\n const output = result[0]?.result as { ok: boolean; summary: string } | undefined;\n const summary = output?.summary ?? \"The page action returned no result.\";\n await audit(output?.ok ? \"action\" : \"error\", summary, { ...(session ? { sessionid: session.id } : {}), ...(plan ? { planid: plan.id } : {}), stepid });\n return output ?? { ok: false, summary };\n}\n\nasync function handlerequest(message: unknown, sender: chrome.runtime.MessageSender): Promise<unknown> {\n if (!extensionpage(sender)) throw new Error(\"Requests are accepted only from Devthink extension pages.\");\n const input = message as { kind?: string; endpoint?: string; objective?: string; stepid?: string };\n switch (input.kind) {\n case \"configure\": {\n const config = normalizeendpoint(input.endpoint ?? \"\");\n const granted = await chrome.permissions.contains({ origins: [hostpattern(config.origin)] });\n if (!granted) throw new Error(\"The endpoint origin has not received optional permission.\");\n await memory.setconfig(config);\n await audit(\"configure\", `Configured user-selected endpoint ${config.origin}.`);\n return config;\n }\n case \"startsession\": return startsession();\n case \"context\": return { config: await memory.getconfig(), session: await memory.getsession(), plan: await memory.getplan(), diagnostic: await memory.getdiagnostic(), audit: await memory.getaudit() };\n case \"diagnostic\": return diagnostic();\n case \"proposelocal\": return propose(input.objective ?? \"\", false);\n case \"proposeremote\": return propose(input.objective ?? \"\", true);\n case \"approve\": {\n const plan = await memory.getplan();\n if (!plan || plan.state !== \"pending\") throw new Error(\"Only a pending plan can be approved.\");\n const approved = { ...plan, state: \"approved\" as const, approvedat: Date.now() };\n await memory.setplan(approved);\n const current = await memory.getsession();\n await audit(\"approval\", \"The user approved the reviewed plan.\", { ...(current ? { sessionid: current.id } : {}), planid: approved.id });\n return approved;\n }\n case \"reject\": {\n const plan = await memory.getplan();\n if (!plan) throw new Error(\"No plan is available to reject.\");\n const rejected = { ...plan, state: \"rejected\" as const };\n await memory.setplan(rejected);\n const current = await memory.getsession();\n await audit(\"approval\", \"The user rejected the plan.\", { ...(current ? { sessionid: current.id } : {}), planid: rejected.id });\n return rejected;\n }\n case \"execute\": return executestep(input.stepid ?? \"\");\n case \"stop\": {\n const session = await memory.getsession();\n if (session) await memory.setsession({ ...session, stoppedat: Date.now() });\n const plan = await memory.getplan();\n if (plan && [\"pending\", \"approved\"].includes(plan.state)) await memory.setplan({ ...plan, state: \"cancelled\" });\n await audit(\"stop\", \"The user stopped the browser session.\", { ...(session ? { sessionid: session.id } : {}), ...(plan ? { planid: plan.id } : {}) });\n return { stopped: true };\n }\n default: throw new Error(\"Unknown Devthink request.\");\n }\n}\n\nchrome.runtime.onMessage.addListener((message, sender, sendresponse) => {\n handlerequest(message, sender).then(value => sendresponse({ ok: true, value })).catch(error => sendresponse({ ok: false, error: error instanceof Error ? error.message : String(error) }));\n return true;\n});\n\nchrome.runtime.onConnect.addListener(port => {\n if (port.name !== \"devthinksidepanel\" || port.sender?.id !== chrome.runtime.id || !port.sender.url?.startsWith(chrome.runtime.getURL(\"\"))) return port.disconnect();\n port.onMessage.addListener(message => { handlerequest(message, port.sender ?? {}).then(value => port.postMessage({ ok: true, value })).catch(error => port.postMessage({ ok: false, error: error instanceof Error ? error.message : String(error) })); });\n});\n"],
5
+ "mappings": ";AAQO,IAAM,gBAAN,MAAoB;AAAA,EACzB,YAA6B,SAAwB;AAAxB;AAAA,EAAyB;AAAA,EAEtD,MAAM,YAAiD;AAAE,WAAO,KAAK,QAAQ,IAAoB,QAAQ;AAAA,EAAG;AAAA,EAC5G,MAAM,UAAU,OAAsC;AAAE,WAAO,KAAK,QAAQ,IAAI,UAAU,KAAK;AAAA,EAAG;AAAA,EAClG,MAAM,aAAgD;AAAE,WAAO,KAAK,QAAQ,IAAkB,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YAAY,EAAE,IAAI,MAAM,MAAM,CAAC,CAAC,EAAE,MAAM,WAAS,KAAK,YAAY,EAAE,IAAI,OAAO,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAE,CAAC,CAAC;AAAA,EAAG,CAAC;AAC1P,CAAC;",
6
+ "names": []
7
+ }
@@ -0,0 +1,26 @@
1
+ {
2
+ "manifest_version": 3,
3
+ "name": "Devthink",
4
+ "version": "1.1.11",
5
+ "description": "A consent-first bridge for reviewed browser-agent tasks.",
6
+ "permissions": [
7
+ "activeTab",
8
+ "storage",
9
+ "scripting",
10
+ "sidePanel"
11
+ ],
12
+ "optional_host_permissions": [
13
+ "https://*/*"
14
+ ],
15
+ "background": {
16
+ "service_worker": "background.js",
17
+ "type": "module"
18
+ },
19
+ "action": {
20
+ "default_title": "Devthink",
21
+ "default_popup": "popup.html"
22
+ },
23
+ "side_panel": {
24
+ "default_path": "sidepanel.html"
25
+ }
26
+ }
@@ -0,0 +1,65 @@
1
+ "use strict";
2
+ (() => {
3
+ // extension/pagebridge.ts
4
+ function bounded(value, length = 180) {
5
+ return value.replace(/\s+/g, " ").trim().slice(0, length);
6
+ }
7
+ function label(element) {
8
+ const aria = element.getAttribute("aria-label");
9
+ const labelledby = element.getAttribute("aria-labelledby");
10
+ const linked = labelledby ? document.getElementById(labelledby)?.textContent : "";
11
+ return bounded(aria || linked || element.getAttribute("title") || element.textContent || "");
12
+ }
13
+ function selector(element) {
14
+ if (element.id) return `#${CSS.escape(element.id)}`;
15
+ const role = element.getAttribute("role");
16
+ const name = element.getAttribute("name");
17
+ if (role && name) return `[role="${CSS.escape(role)}"][name="${CSS.escape(name)}"]`;
18
+ if (name) return `${element.tagName.toLowerCase()}[name="${CSS.escape(name)}"]`;
19
+ const tag = element.tagName.toLowerCase();
20
+ const parent = element.parentElement;
21
+ if (!parent) return tag;
22
+ const peers = [...parent.children].filter((node) => node.tagName === element.tagName);
23
+ return `${tag}:nth-of-type(${peers.indexOf(element) + 1})`;
24
+ }
25
+ function capturesnapshot() {
26
+ const candidates = [...document.querySelectorAll("a[href], button, input, textarea, select, [role=button], [role=link]")].slice(0, 80);
27
+ const interactive = candidates.map((element) => ({ selector: selector(element), role: element.getAttribute("role") || element.tagName.toLowerCase(), label: label(element) })).filter((item) => item.label || item.role);
28
+ const forms = [...document.querySelectorAll("input, textarea, select")].slice(0, 40).map((element) => ({ label: label(element), type: element.getAttribute("type") || element.tagName.toLowerCase(), name: element.getAttribute("name") || "" }));
29
+ const text = bounded(document.body?.innerText || "", 2e3);
30
+ return { url: location.href, title: bounded(document.title, 180), textpreview: text, textlength: document.body?.innerText.length ?? 0, forms, interactive, capturedat: Date.now() };
31
+ }
32
+ function performstep(step, expectedorigin) {
33
+ if (location.origin !== expectedorigin) return { ok: false, summary: "Page origin changed before action." };
34
+ if (step.kind === "observe") return { ok: true, summary: "Observation completed." };
35
+ if (step.kind === "navigate") {
36
+ if (!step.value || new URL(step.value).origin !== expectedorigin) return { ok: false, summary: "Navigation target is outside the approved origin." };
37
+ location.assign(step.value);
38
+ return { ok: true, summary: "Navigation request sent." };
39
+ }
40
+ if (!step.target) return { ok: false, summary: "Action target is absent." };
41
+ const target = document.querySelector(step.target);
42
+ if (!(target instanceof HTMLElement)) return { ok: false, summary: "Action target is no longer available." };
43
+ if (step.kind === "focus") {
44
+ target.focus();
45
+ return { ok: true, summary: "Target focused." };
46
+ }
47
+ if (step.kind === "inspect") return { ok: true, summary: `Target: ${label(target) || target.tagName.toLowerCase()}.` };
48
+ if (step.kind === "click") {
49
+ target.click();
50
+ return { ok: true, summary: "Reviewed click completed." };
51
+ }
52
+ if (step.kind === "type") {
53
+ if (!(target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement)) return { ok: false, summary: "Target cannot receive text." };
54
+ if (typeof step.value !== "string") return { ok: false, summary: "Approved text is absent." };
55
+ target.focus();
56
+ target.value = step.value;
57
+ target.dispatchEvent(new Event("input", { bubbles: true }));
58
+ target.dispatchEvent(new Event("change", { bubbles: true }));
59
+ return { ok: true, summary: "Approved text entered." };
60
+ }
61
+ return { ok: false, summary: "Unsupported action." };
62
+ }
63
+ Object.assign(globalThis, { devthinkbridge: { capturesnapshot, performstep } });
64
+ })();
65
+ //# sourceMappingURL=pagebridge.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../pagebridge.ts"],
4
+ "sourcesContent": ["import type { observation, toolstep } from \"../types.js\";\n\nfunction bounded(value: string, length = 180): string {\n return value.replace(/\\s+/g, \" \").trim().slice(0, length);\n}\n\nfunction label(element: Element): string {\n const aria = element.getAttribute(\"aria-label\");\n const labelledby = element.getAttribute(\"aria-labelledby\");\n const linked = labelledby ? document.getElementById(labelledby)?.textContent : \"\";\n return bounded(aria || linked || element.getAttribute(\"title\") || element.textContent || \"\");\n}\n\nfunction selector(element: Element): string {\n if (element.id) return `#${CSS.escape(element.id)}`;\n const role = element.getAttribute(\"role\");\n const name = element.getAttribute(\"name\");\n if (role && name) return `[role=\"${CSS.escape(role)}\"][name=\"${CSS.escape(name)}\"]`;\n if (name) return `${element.tagName.toLowerCase()}[name=\"${CSS.escape(name)}\"]`;\n const tag = element.tagName.toLowerCase();\n const parent = element.parentElement;\n if (!parent) return tag;\n const peers = [...parent.children].filter(node => node.tagName === element.tagName);\n return `${tag}:nth-of-type(${peers.indexOf(element) + 1})`;\n}\n\n/** Captures only semantic, bounded page context for a user-approved active tab. */\nexport function capturesnapshot(): observation {\n const candidates = [...document.querySelectorAll(\"a[href], button, input, textarea, select, [role=button], [role=link]\")].slice(0, 80);\n const interactive = candidates.map(element => ({ selector: selector(element), role: element.getAttribute(\"role\") || element.tagName.toLowerCase(), label: label(element) })).filter(item => item.label || item.role);\n const forms = [...document.querySelectorAll(\"input, textarea, select\")].slice(0, 40).map(element => ({ label: label(element), type: element.getAttribute(\"type\") || element.tagName.toLowerCase(), name: element.getAttribute(\"name\") || \"\" }));\n const text = bounded(document.body?.innerText || \"\", 2000);\n return { url: location.href, title: bounded(document.title, 180), textpreview: text, textlength: document.body?.innerText.length ?? 0, forms, interactive, capturedat: Date.now() };\n}\n\n/** Performs one local action after the background policy gate and a fresh target check. */\nexport function performstep(step: toolstep, expectedorigin: string): { ok: boolean; summary: string } {\n if (location.origin !== expectedorigin) return { ok: false, summary: \"Page origin changed before action.\" };\n if (step.kind === \"observe\") return { ok: true, summary: \"Observation completed.\" };\n if (step.kind === \"navigate\") {\n if (!step.value || new URL(step.value).origin !== expectedorigin) return { ok: false, summary: \"Navigation target is outside the approved origin.\" };\n location.assign(step.value);\n return { ok: true, summary: \"Navigation request sent.\" };\n }\n if (!step.target) return { ok: false, summary: \"Action target is absent.\" };\n const target = document.querySelector(step.target);\n if (!(target instanceof HTMLElement)) return { ok: false, summary: \"Action target is no longer available.\" };\n if (step.kind === \"focus\") { target.focus(); return { ok: true, summary: \"Target focused.\" }; }\n if (step.kind === \"inspect\") return { ok: true, summary: `Target: ${label(target) || target.tagName.toLowerCase()}.` };\n if (step.kind === \"click\") { target.click(); return { ok: true, summary: \"Reviewed click completed.\" }; }\n if (step.kind === \"type\") {\n if (!(target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement)) return { ok: false, summary: \"Target cannot receive text.\" };\n if (typeof step.value !== \"string\") return { ok: false, summary: \"Approved text is absent.\" };\n target.focus();\n target.value = step.value;\n target.dispatchEvent(new Event(\"input\", { bubbles: true }));\n target.dispatchEvent(new Event(\"change\", { bubbles: true }));\n return { ok: true, summary: \"Approved text entered.\" };\n }\n return { ok: false, summary: \"Unsupported action.\" };\n}\n\nObject.assign(globalThis, { devthinkbridge: { capturesnapshot, performstep } });\n"],
5
+ "mappings": ";;;AAEA,WAAS,QAAQ,OAAe,SAAS,KAAa;AACpD,WAAO,MAAM,QAAQ,QAAQ,GAAG,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM;AAAA,EAC1D;AAEA,WAAS,MAAM,SAA0B;AACvC,UAAM,OAAO,QAAQ,aAAa,YAAY;AAC9C,UA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AACxG,QAAI,KAAK,SAAS,QAAQ;AACxB,UAAI,EAAE,kBAAkB,oBAAoB,kBAAkB,qBAAsB,QAAO,EAAE,IAAI,OAAO,SAAS,8BAA8B;AAC/I,UAAI,OAAO,KAAK,UAAU,SAAU,QAAO,EAAE,IAAI,OAAO,SAAS,2BAA2B;AAC5F,aAAO,MAAM;AACb,aAAO,QAAQ,KAAK;AACpB,aAAO,cAAc,IAAI,MAAM,SAAS,EAAE,SAAS,KAAK,CAAC,CAAC;AAC1D,aAAO,cAAc,IAAI,MAAM,UAAU,EAAE,SAAS,KAAK,CAAC,CAAC;AAC3D,aAAO,EAAE,IAAI,MAAM,SAAS,yBAAyB;AAAA,IACvD;AACA,WAAO,EAAE,IAAI,OAAO,SAAS,sBAAsB;AAAA,EACrD;AAEA,SAAO,OAAO,YAAY,EAAE,gBAAgB,EAAE,iBAAiB,YAAY,EAAE,CAAC;",
6
+ "names": []
7
+ }
@@ -0,0 +1,5 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Devthink</title><link rel="stylesheet" href="style.css"></head>
4
+ <body><main><header><p class="eyebrow">DEVTHINK 1.1.11</p><h1>Browser bridge</h1><p>Consent is required before page access or action.</p></header><label for="endpoint">Optional agent endpoint</label><input id="endpoint" type="url" inputmode="url" placeholder="https://agent.example/proposal" autocomplete="off"><button id="connect">Approve endpoint origin</button><div class="actions"><button id="session">Start active tab session</button><button id="openpanel" class="secondary">Review plans</button><button id="stop" class="danger">Stop</button></div><p id="status" role="status">Loading session state.</p></main><script type="module" src="popup.js"></script></body>
5
+ </html>
@@ -0,0 +1,67 @@
1
+ // policy.ts
2
+ function normalizeendpoint(value) {
3
+ const endpoint = new URL(value.trim());
4
+ if (endpoint.protocol !== "https:") throw new Error("Devthink accepts HTTPS endpoints only.");
5
+ if (endpoint.username || endpoint.password) throw new Error("Endpoint credentials are not allowed in the URL.");
6
+ return { endpoint: endpoint.toString(), origin: endpoint.origin, configuredat: Date.now() };
7
+ }
8
+ function hostpattern(origin) {
9
+ const parsed = new URL(origin);
10
+ if (parsed.protocol !== "https:") throw new Error("Only HTTPS origins can be granted.");
11
+ return `${parsed.origin}/*`;
12
+ }
13
+
14
+ // extension/popup.ts
15
+ var endpointinput = document.querySelector("#endpoint");
16
+ var statusnode = document.querySelector("#status");
17
+ var connectbutton = document.querySelector("#connect");
18
+ var sessionbutton = document.querySelector("#session");
19
+ var stopbutton = document.querySelector("#stop");
20
+ var openbutton = document.querySelector("#openpanel");
21
+ function status(message, error = false) {
22
+ if (statusnode) {
23
+ statusnode.textContent = message;
24
+ statusnode.dataset.state = error ? "error" : "ready";
25
+ }
26
+ }
27
+ async function request(message) {
28
+ const response = await chrome.runtime.sendMessage(message);
29
+ if (!response.ok) throw new Error(response.error);
30
+ return response.value;
31
+ }
32
+ async function restore() {
33
+ const context = await request({ kind: "context" });
34
+ if (endpointinput && context.config) endpointinput.value = context.config.endpoint;
35
+ const active = context.session && !context.session.stoppedat && context.session.expiresat > Date.now();
36
+ status(active ? "Session active. Review the plan in the side panel." : "No active browser session.");
37
+ }
38
+ connectbutton?.addEventListener("click", async () => {
39
+ try {
40
+ const config = normalizeendpoint(endpointinput?.value ?? "");
41
+ const granted = await chrome.permissions.request({ origins: [hostpattern(config.origin)] });
42
+ if (!granted) throw new Error("Origin permission was not granted.");
43
+ await request({ kind: "configure", endpoint: config.endpoint });
44
+ status(`Endpoint approved for ${config.origin}.`);
45
+ } catch (error) {
46
+ status(error instanceof Error ? error.message : String(error), true);
47
+ }
48
+ });
49
+ sessionbutton?.addEventListener("click", async () => {
50
+ try {
51
+ await request({ kind: "startsession" });
52
+ status("Session started for the active HTTPS tab.");
53
+ } catch (error) {
54
+ status(error instanceof Error ? error.message : String(error), true);
55
+ }
56
+ });
57
+ stopbutton?.addEventListener("click", async () => {
58
+ try {
59
+ await request({ kind: "stop" });
60
+ status("Session stopped. No action can continue.");
61
+ } catch (error) {
62
+ status(error instanceof Error ? error.message : String(error), true);
63
+ }
64
+ });
65
+ openbutton?.addEventListener("click", () => chrome.sidePanel.open({ windowId: chrome.windows.WINDOW_ID_CURRENT }));
66
+ restore().catch((error) => status(error instanceof Error ? error.message : String(error), true));
67
+ //# sourceMappingURL=popup.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../policy.ts", "../popup.ts"],
4
+ "sourcesContent": ["import type { actionkind, agentplan, agentsession, endpointconfig, policyevaluation, toolstep } from \"./types.js\";\n\nconst sensitiveactions = new Set<actionkind>([\"click\", \"type\", \"navigate\"]);\nconst allowedactions = new Set<actionkind>([\"observe\", \"inspect\", \"focus\", \"click\", \"type\", \"navigate\"]);\n\n/** Normalizes a user supplied HTTPS endpoint without preserving a provider lock-in. */\nexport function normalizeendpoint(value: string): endpointconfig {\n const endpoint = new URL(value.trim());\n if (endpoint.protocol !== \"https:\") throw new Error(\"Devthink accepts HTTPS endpoints only.\");\n if (endpoint.username || endpoint.password) throw new Error(\"Endpoint credentials are not allowed in the URL.\");\n return { endpoint: endpoint.toString(), origin: endpoint.origin, configuredat: Date.now() };\n}\n\n/** Creates the exact optional host pattern requested from Chromium. */\nexport function hostpattern(origin: string): string {\n const parsed = new URL(origin);\n if (parsed.protocol !== \"https:\") throw new Error(\"Only HTTPS origins can be granted.\");\n return `${parsed.origin}/*`;\n}\n\n/** Defines action risk from a fixed local allowlist. */\nexport function actionrisk(kind: actionkind): \"read\" | \"interaction\" | \"sensitive\" {\n if (!allowedactions.has(kind)) throw new Error(\"Unsupported browser action.\");\n if (sensitiveactions.has(kind)) return \"sensitive\";\n return kind === \"focus\" ? \"interaction\" : \"read\";\n}\n\n/** Validates a single proposal against the active tab origin and local policy. */\nexport function validatestep(step: toolstep, origin: string): policyevaluation {\n if (!allowedactions.has(step.kind)) return { allowed: false, reason: \"Unsupported action kind.\" };\n if (!step.summary.trim()) return { allowed: false, reason: \"A human-readable action summary is required.\" };\n if ((step.kind === \"click\" || step.kind === \"focus\" || step.kind === \"inspect\" || step.kind === \"type\") && !step.target?.trim()) return { allowed: false, reason: \"A page target is required.\" };\n if (step.kind === \"navigate\") {\n if (!step.value) return { allowed: false, reason: \"A navigation URL is required.\" };\n try {\n if (new URL(step.value).origin !== origin) return { allowed: false, reason: \"Navigation must remain within the approved origin.\" };\n } catch {\n return { allowed: false, reason: \"Navigation URL is invalid.\" };\n }\n }\n return { allowed: true };\n}\n\n/** Applies the consent gate immediately before an action reaches the page bridge. */\nexport function canexecute(input: { session: agentsession | undefined; plan: agentplan | undefined; step: toolstep; tabid: number; origin: string; now?: number }): policyevaluation {\n const now = input.now ?? Date.now();\n if (!input.session || input.session.stoppedat) return { allowed: false, reason: \"No active browser session exists.\" };\n if (input.session.expiresat <= now) return { allowed: false, reason: \"The browser session has expired.\" };\n if (input.session.tabid !== input.tabid || input.session.origin !== input.origin) return { allowed: false, reason: \"The action is outside the approved tab or origin.\" };\n if (!input.plan || input.plan.state !== \"approved\") return { allowed: false, reason: \"The plan has not received explicit approval.\" };\n if (input.plan.expiresat <= now) return { allowed: false, reason: \"The approved plan has expired.\" };\n return validatestep(input.step, input.origin);\n}\n", "import { hostpattern, normalizeendpoint } from \"../policy.js\";\n\nconst endpointinput = document.querySelector<HTMLInputElement>(\"#endpoint\");\nconst statusnode = document.querySelector<HTMLElement>(\"#status\");\nconst connectbutton = document.querySelector<HTMLButtonElement>(\"#connect\");\nconst sessionbutton = document.querySelector<HTMLButtonElement>(\"#session\");\nconst stopbutton = document.querySelector<HTMLButtonElement>(\"#stop\");\nconst openbutton = document.querySelector<HTMLButtonElement>(\"#openpanel\");\n\nfunction status(message: string, error = false): void { if (statusnode) { statusnode.textContent = message; statusnode.dataset.state = error ? \"error\" : \"ready\"; } }\nasync function request(message: unknown): Promise<unknown> { const response = await chrome.runtime.sendMessage(message) as { ok: boolean; value?: unknown; error?: string }; if (!response.ok) throw new Error(response.error); return response.value; }\n\nasync function restore(): Promise<void> {\n const context = await request({ kind: \"context\" }) as { config?: { endpoint: string }; session?: { stoppedat?: number; expiresat: number } };\n if (endpointinput && context.config) endpointinput.value = context.config.endpoint;\n const active = context.session && !context.session.stoppedat && context.session.expiresat > Date.now();\n status(active ? \"Session active. Review the plan in the side panel.\" : \"No active browser session.\");\n}\n\nconnectbutton?.addEventListener(\"click\", async () => {\n try {\n const config = normalizeendpoint(endpointinput?.value ?? \"\");\n const granted = await chrome.permissions.request({ origins: [hostpattern(config.origin)] });\n if (!granted) throw new Error(\"Origin permission was not granted.\");\n await request({ kind: \"configure\", endpoint: config.endpoint });\n status(`Endpoint approved for ${config.origin}.`);\n } catch (error) { status(error instanceof Error ? error.message : String(error), true); }\n});\nsessionbutton?.addEventListener(\"click\", async () => { try { await request({ kind: \"startsession\" }); status(\"Session started for the active HTTPS tab.\"); } catch (error) { status(error instanceof Error ? error.message : String(error), true); } });\nstopbutton?.addEventListener(\"click\", async () => { try { await request({ kind: \"stop\" }); status(\"Session stopped. No action can continue.\"); } catch (error) { status(error instanceof Error ? error.message : String(error), true); } });\nopenbutton?.addEventListener(\"click\", () => chrome.sidePanel.open({ windowId: chrome.windows.WINDOW_ID_CURRENT }));\nrestore().catch(error => status(error instanceof Error ? error.message : String(error), true));\n"],
5
+ "mappings": ";AAMO,SAAS,kBAAkB,OAA+B;AAC/D,QAAM,WAAW,IAAI,IAAI,MAAM,KAAK,CAAC;AACrC,MAAI,SAAS,aAAa,SAAU,OAAM,IAAI,MAAM,wCAAwC;AAC5F,MAAI,SAAS,YAAY,SAAS,SAAU,OAAM,IAAI,MAAM,kDAAkD;AAC9G,SAAO,EAAE,UAAU,SAAS,SAAS,GAAG,QAAQ,SAAS,QAAQ,cAAc,KAAK,IAAI,EAAE;AAC5F;AAGO,SAAS,YAAY,QAAwB;AAClD,QAAM,SAAS,IAAI,IAAI,MAAM;AAC7B,MAAI,OAAO,aAAa,SAAU,OAAM,IAAI,MAAM,oCAAoC;AACtF,SAAO,GAAG,OAAO,MAAM;AACzB;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A,EAAG;AAC1F,CAAC;AACD,eAAe,iBAAiB,SAAS,YAAY;AAAE,MAAI;AAAE,UAAM,QAAQ,EAAE,MAAM,eAAe,CAAC;AAAG,WAAO,2CAA2C;AAAA,EAAG,SAAS,OAAO;AAAE,WAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAAG,IAAI;AAAA,EAAG;AAAE,CAAC;AACtP,YAAY,iBAAiB,SAAS,YAAY;AAAE,MAAI;AAAE,UAAM,QAAQ,EAAE,MAAM,OAAO,CAAC;AAAG,WAAO,0CAA0C;AAAA,EAAG,SAAS,OAAO;AAAE,WAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAAG,IAAI;AAAA,EAAG;AAAE,CAAC;AAC1O,YAAY,iBAAiB,SAAS,MAAM,OAAO,UAAU,KAAK,EAAE,UAAU,OAAO,QAAQ,kBAAkB,CAAC,CAAC;AACjH,QAAQ,EAAE,MAAM,WAAS,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAAG,IAAI,CAAC;",
6
+ "names": []
7
+ }
@@ -0,0 +1,5 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Devthink review</title><link rel="stylesheet" href="style.css"></head>
4
+ <body><main class="wide"><header><p class="eyebrow">REVIEW GATE</p><h1>Plan before action</h1><p>Every browser operation remains blocked until the user reviews and approves it here.</p></header><label for="objective">Objective</label><textarea id="objective" rows="4" placeholder="Describe a browser task to turn into a reviewable plan."></textarea><div class="actions"><button id="localplan">Create local observation plan</button><button id="remoteplan" class="secondary">Ask configured endpoint</button><button id="diagnostic" class="secondary">Capture local diagnostics</button></div><p id="status" role="status">Loading session state.</p><section><h2>Current plan</h2><div id="plan" class="panel"></div></section><section><h2>Structured diagnostics</h2><ul id="diagnostics" class="audit"></ul></section><section><h2>Local audit</h2><ol id="audit" class="audit"></ol></section></main><script type="module" src="sidepanel.js"></script></body>
5
+ </html>