@qilin-agent/experimental-browser-use-runtime 0.0.0-stage → 3.1.4
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/LICENSE +21 -0
- package/README.i18n.yaml +37 -0
- package/README.md +94 -2
- package/README.zh.md +95 -0
- package/lib/index.js +155 -0
- package/lib/types/index.d.ts +78 -0
- package/lib/types/index.js +166 -0
- package/lib/types/mcp.d.ts +58 -0
- package/lib/types/mcp.js +172 -0
- package/package.json +64 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 kkutysllb
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.i18n.yaml
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
# Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading
|
|
2
|
+
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
|
|
3
|
+
# After editing either side, bring the other along and re-record with:
|
|
4
|
+
# pnpm run verify-translation-pairing --write packages/experimental/browser-use-runtime/README.md
|
|
5
|
+
/:
|
|
6
|
+
en: 32bd01db6a5146ed
|
|
7
|
+
zh: 31e56827b98bc1b3
|
|
8
|
+
/qilin-agent-experimental-browser-use-runtime:
|
|
9
|
+
en: 4eba6b7208987b20
|
|
10
|
+
zh: 922dacb855eb512c
|
|
11
|
+
/qilin-agent-experimental-browser-use-runtime/summary:
|
|
12
|
+
en: ac29eb4a94d3cbff
|
|
13
|
+
zh: 66f2e800cabb19aa
|
|
14
|
+
/qilin-agent-experimental-browser-use-runtime/table-of-contents:
|
|
15
|
+
en: d152484eb41ac6b4
|
|
16
|
+
zh: f14f34fce35a8d90
|
|
17
|
+
/qilin-agent-experimental-browser-use-runtime/use-this-package:
|
|
18
|
+
en: 93d850b5306a182a
|
|
19
|
+
zh: edb03c1c87d8d7cc
|
|
20
|
+
/qilin-agent-experimental-browser-use-runtime/understand-the-implementation:
|
|
21
|
+
en: 5df9e4e6de98d614
|
|
22
|
+
zh: 82ee28e9d31ab6fa
|
|
23
|
+
/qilin-agent-experimental-browser-use-runtime/further-exploration:
|
|
24
|
+
en: 5894be0f95632120
|
|
25
|
+
zh: 732e35051fdda16a
|
|
26
|
+
/qilin-agent-experimental-browser-use-runtime/model-experience:
|
|
27
|
+
en: 705441e08df596c9
|
|
28
|
+
zh: d70a7ba9611daca5
|
|
29
|
+
/qilin-agent-experimental-browser-use-runtime/model-experience/kv-cache-effect:
|
|
30
|
+
en: 68b91a73746b663a
|
|
31
|
+
zh: 18f6d14457ed81d9
|
|
32
|
+
/qilin-agent-experimental-browser-use-runtime/known-limitations-and-deferred-work:
|
|
33
|
+
en: 5a3a9c35a8097d30
|
|
34
|
+
zh: 9e67f2c4279becf7
|
|
35
|
+
/qilin-agent-experimental-browser-use-runtime/known-limitations-and-deferred-work/dev-note:
|
|
36
|
+
en: e67f633dc6fe7773
|
|
37
|
+
zh: 8ec3e73528ddb1a6
|
package/README.md
CHANGED
|
@@ -1,3 +1,95 @@
|
|
|
1
|
-
|
|
1
|
+
---
|
|
2
|
+
description: "Share per-Session browser ownership and MCP activation across experimental browser providers."
|
|
3
|
+
kind: "package-library"
|
|
4
|
+
---
|
|
2
5
|
|
|
3
|
-
|
|
6
|
+
# @qilin-agent/experimental-browser-use-runtime
|
|
7
|
+
|
|
8
|
+
English | [中文](README.zh.md)
|
|
9
|
+
|
|
10
|
+
## Summary
|
|
11
|
+
|
|
12
|
+
Browser providers use this library to reuse a browser across one Session's turns and close its resources when that Session's runtime is disposed. Operations for one Session run in order, while isolated Sessions can proceed independently. Attachment mode reserves one external browser for a single Session. The library also connects provider-owned MCP servers and discovers their tools before the Session's first model request.
|
|
13
|
+
|
|
14
|
+
## Table of Contents
|
|
15
|
+
|
|
16
|
+
- [Use this package](#use-this-package)
|
|
17
|
+
- [Understand the implementation](#understand-the-implementation)
|
|
18
|
+
- [Further Exploration](#further-exploration)
|
|
19
|
+
- [Model Experience](#model-experience)
|
|
20
|
+
- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work)
|
|
21
|
+
- [Dev Note](#dev-note)
|
|
22
|
+
|
|
23
|
+
-----
|
|
24
|
+
|
|
25
|
+
<a id="use-this-package"></a>
|
|
26
|
+
## Use this package
|
|
27
|
+
|
|
28
|
+
This public experimental library is a dependency of the browser providers. It has no plugin entry or mount configuration. The [browser-use service](../../browser-use/browser-use/README.md) remains independent of the library.
|
|
29
|
+
|
|
30
|
+
Native providers construct `SessionResources` from the package root, supplying resource acquisition and cleanup callbacks. Calls pass the exact live Agent to `run()`; stale owners and a second owner of an exclusive attachment fail before acquisition. Canceling an acquisition wait leaves initialization available to other callers in the same Session; Session disposal aborts and awaits that initialization. Providers keep their registration until `dispose()` finishes.
|
|
31
|
+
|
|
32
|
+
MCP providers use `mountSessionMcp` from `@qilin-agent/experimental-browser-use-runtime/mcp`, supplying their fixed server name, executable, arguments, and ownership policy. The helper awaits one scoped client startup and discovery attempt within each future Agent's `agent/created` event. Agent creation or resume completes after discovery, before queued input runs; a successful client remains owned by that Session across turns.
|
|
33
|
+
|
|
34
|
+
A busy attachment skips startup permanently for that live activation while its other work continues. Releasing the attachment does not retry skipped activations; a newly created or resumed Agent can acquire it. Startup failure or cancellation rejects Agent creation or resume and triggers creation rollback, including client cleanup. Reconnection is disabled. Loading or reloading a provider applies only to future Agent activations.
|
|
35
|
+
|
|
36
|
+
Callers can inspect prompt assembly and scoped tool definitions after awaited Agent creation or resume completes.
|
|
37
|
+
|
|
38
|
+
Browser tools and resource requests targeting this server use the same queue and require the calling Session's own connection. Other MCP servers remain usable. Inherited server instructions are omitted without ownership; the shared server-name inventory keeps its normal scope behavior.
|
|
39
|
+
|
|
40
|
+
-----
|
|
41
|
+
|
|
42
|
+
<a id="understand-the-implementation"></a>
|
|
43
|
+
## Understand the implementation
|
|
44
|
+
|
|
45
|
+
<details>
|
|
46
|
+
<summary>Implementation internals — click to expand</summary>
|
|
47
|
+
|
|
48
|
+
The [resource manager](src/index.ts) keys ownership by live Agent identity and joins operation cancellation with owner disposal. Each resource has one acquisition promise and one operation queue. Failed acquisition releases its reservation only after the provider callback rolls back acquired resources.
|
|
49
|
+
|
|
50
|
+
Disposed-cause cancellation starts resource cleanup before AgentHandle waits for idle. Cleanup closes resources before waiting for running operations, allowing connection teardown to interrupt upstream APIs without abort support. A failed close rejects disposal and retains ownership. Agent-scoped cleanup prevents a resumed Session with the same durable id from inheriting a previous browser.
|
|
51
|
+
|
|
52
|
+
The [MCP helper](src/mcp.ts) connects within serial `agent/created`; [AgentLoop](../../core/agent-loop/README.md#understand-the-implementation) holds queued input and owns creation rollback. Prompt assembly reads the initialized catalog. The helper retains the provider registration through resource cleanup and uses the [MCP client](../../mcp/mcp-client/README.md) for transport, schema discovery, result conversion, and durable image admission.
|
|
53
|
+
|
|
54
|
+
</details>
|
|
55
|
+
|
|
56
|
+
-----
|
|
57
|
+
|
|
58
|
+
<a id="further-exploration"></a>
|
|
59
|
+
## Further Exploration
|
|
60
|
+
|
|
61
|
+
- [Browser use](../../../docs/subsystems/browser-use.md) — provider selection and Session ownership.
|
|
62
|
+
- [MCP client](../../mcp/mcp-client/README.md) — discovery, cancellation, and result admission.
|
|
63
|
+
- [Browser ownership decision](../../../.agents/notes/implemented/architecture/2026-09-12-browser-use-provider-registration.md) — registration-only service and resource lifetime.
|
|
64
|
+
|
|
65
|
+
-----
|
|
66
|
+
|
|
67
|
+
<a id="model-experience"></a>
|
|
68
|
+
## Model Experience
|
|
69
|
+
|
|
70
|
+
Indirectly, through provider-owned browser tools, whose catalogs the MCP helper discovers before model request assembly; providers and the MCP client own descriptions, schemas, results, and image behavior.
|
|
71
|
+
|
|
72
|
+
#### KV Cache effect
|
|
73
|
+
|
|
74
|
+
The library adds no prompt text. Discovered tool schemas and provider guidance determine request-prefix changes; ordinary browser resource reuse does not alter those schemas.
|
|
75
|
+
|
|
76
|
+
## Known Limitations and Deferred Work
|
|
77
|
+
|
|
78
|
+
<a id="known-limitations-and-deferred-work"></a>
|
|
79
|
+
|
|
80
|
+
Providers remain responsible for the browser operations they supply.
|
|
81
|
+
|
|
82
|
+
- **MCP activation** — providers do not adopt existing live Agents; a busy attachment is not retried within that activation.
|
|
83
|
+
- **Attachment scope** — exclusive ownership applies to one resource manager, not separate providers, processes, or external browser clients.
|
|
84
|
+
- **Cancellation** — abort signals and connection closure cannot undo browser actions already delivered. An upstream operation that ignores both can delay cleanup.
|
|
85
|
+
- **Recovery** — a failed close retains ownership; this manager does not retry disposal or restore browser state from the Session log.
|
|
86
|
+
|
|
87
|
+
<a id="dev-note"></a>
|
|
88
|
+
### Dev Note
|
|
89
|
+
|
|
90
|
+
<details>
|
|
91
|
+
<summary>Working context for maintainers — click to expand</summary>
|
|
92
|
+
|
|
93
|
+
None.
|
|
94
|
+
|
|
95
|
+
</details>
|
package/README.zh.md
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
---
|
|
2
|
+
description: "在实验性浏览器提供方之间共享按 Session 管理的浏览器所有权与 MCP 激活。"
|
|
3
|
+
kind: "package-library"
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# @qilin-agent/experimental-browser-use-runtime
|
|
7
|
+
|
|
8
|
+
[English](README.md) | 中文
|
|
9
|
+
|
|
10
|
+
## 概述
|
|
11
|
+
|
|
12
|
+
浏览器提供方使用此库,在一个 Session 的多个轮次之间复用浏览器,并在该 Session 的运行时释放时关闭其资源。一个 Session 的操作按顺序运行,隔离的 Session 则可以独立推进。附加模式将一个外部浏览器保留给单个 Session。此库还连接提供方拥有的 MCP 服务器,并在 Session 首次模型请求前发现其工具。
|
|
13
|
+
|
|
14
|
+
## 目录
|
|
15
|
+
|
|
16
|
+
- [使用本包](#use-this-package)
|
|
17
|
+
- [理解实现](#understand-the-implementation)
|
|
18
|
+
- [延伸阅读](#further-exploration)
|
|
19
|
+
- [模型体验](#model-experience)
|
|
20
|
+
- [已知限制与延期工作](#known-limitations-and-deferred-work)
|
|
21
|
+
- [开发备注](#dev-note)
|
|
22
|
+
|
|
23
|
+
-----
|
|
24
|
+
|
|
25
|
+
<a id="use-this-package"></a>
|
|
26
|
+
## 使用本包
|
|
27
|
+
|
|
28
|
+
此公共实验性库是浏览器提供方的依赖。它没有插件入口或挂载配置。[浏览器操作服务](../../browser-use/browser-use/README.zh.md)保持独立于此库。
|
|
29
|
+
|
|
30
|
+
原生提供方从包根入口构造 `SessionResources`,提供资源获取与清理回调。调用向 `run()` 传递确切的实时 Agent;失效的所有者与独占附加的第二个所有者在获取资源前失败。取消资源获取等待不会终止初始化,同一 Session 的其他调用方仍可继续等待;释放 Session 会中止并等待该初始化结束。提供方将注册保留到 `dispose()` 完成。
|
|
31
|
+
|
|
32
|
+
MCP 提供方使用 `@qilin-agent/experimental-browser-use-runtime/mcp` 中的 `mountSessionMcp`,提供固定服务器名称、可执行文件、参数与所有权策略。辅助库在每个后续 Agent 的 `agent/created` 事件中等待一次有作用域的客户端启动与发现尝试。Agent 创建或恢复在发现完成后结束,随后才运行排队输入;成功的客户端跨轮次归该 Session 所有。
|
|
33
|
+
|
|
34
|
+
附加连接被占用时,本次激活永久跳过启动,但其他工作继续运行。连接释放不会触发被跳过激活的重试;新创建或恢复的 Agent 可以获取连接。启动失败或取消会拒绝 Agent 创建或恢复,并触发包含客户端清理的创建回滚。重连已禁用。加载或重新加载提供方只作用于后续的 Agent 激活。
|
|
35
|
+
|
|
36
|
+
调用方在等待 Agent 创建或恢复完成后,即可检查提示词组装和作用域工具定义。
|
|
37
|
+
|
|
38
|
+
指向此服务器的浏览器工具调用与资源请求使用同一队列,且要求调用 Session 自己拥有连接。其他 MCP 服务器仍可使用。没有所有权时会省略继承的服务器指导;共享服务器名称目录保留常规作用域行为。
|
|
39
|
+
|
|
40
|
+
-----
|
|
41
|
+
|
|
42
|
+
<a id="understand-the-implementation"></a>
|
|
43
|
+
## 理解实现
|
|
44
|
+
|
|
45
|
+
<details>
|
|
46
|
+
<summary>实现内部机制 — 点击展开</summary>
|
|
47
|
+
|
|
48
|
+
[资源管理器](src/index.ts)以实时 Agent 身份为所有权键,并将操作取消与所有者释放关联起来。每个资源只有一个获取 promise 和一个操作队列。获取失败时,仅在提供方回调回滚已获取资源后释放保留。
|
|
49
|
+
|
|
50
|
+
因释放而取消时,在 AgentHandle 等待空闲前开始资源清理。清理先关闭资源再等待运行中的操作,使连接清理能够中断不支持 abort 的上游 API。关闭失败会拒绝释放并保留所有权。Agent 作用域清理防止使用同一持久 id 恢复的 Session 继承之前的浏览器。
|
|
51
|
+
|
|
52
|
+
[MCP 辅助库](src/mcp.ts)在串行 `agent/created` 中建立连接;[AgentLoop](../../core/agent-loop/README.zh.md#understand-the-implementation)保留排队输入并负责创建回滚。提示词组装读取已初始化的目录。辅助库在资源清理期间保留提供方注册,并通过 [MCP 客户端](../../mcp/mcp-client/README.zh.md)处理传输、schema 发现、结果转换与持久图像接纳。
|
|
53
|
+
|
|
54
|
+
</details>
|
|
55
|
+
|
|
56
|
+
-----
|
|
57
|
+
|
|
58
|
+
<a id="further-exploration"></a>
|
|
59
|
+
## 延伸阅读
|
|
60
|
+
|
|
61
|
+
- [浏览器操作](../../../docs/subsystems/browser-use.zh.md) — 提供方选择与 Session 所有权。
|
|
62
|
+
- [MCP 客户端](../../mcp/mcp-client/README.zh.md) — 发现、取消与结果接纳。
|
|
63
|
+
- [浏览器所有权决策](../../../.agents/notes/implemented/architecture/2026-09-12-browser-use-provider-registration.zh.md) — 仅注册名称的服务与资源生命周期。
|
|
64
|
+
|
|
65
|
+
-----
|
|
66
|
+
|
|
67
|
+
<a id="model-experience"></a>
|
|
68
|
+
## 模型体验
|
|
69
|
+
|
|
70
|
+
通过提供方拥有的浏览器工具间接影响模型,MCP 辅助库在模型请求组装前发现其目录;提供方与 MCP 客户端拥有描述、schema、结果与图像行为。
|
|
71
|
+
|
|
72
|
+
#### KV Cache 影响
|
|
73
|
+
|
|
74
|
+
此库不添加提示文本。发现的工具 schema 与提供方指导决定请求前缀变化;常规浏览器资源复用不改变这些 schema。
|
|
75
|
+
|
|
76
|
+
## 已知限制与延期工作
|
|
77
|
+
|
|
78
|
+
<a id="known-limitations-and-deferred-work"></a>
|
|
79
|
+
|
|
80
|
+
提供方仍负责自己提供的浏览器操作。
|
|
81
|
+
|
|
82
|
+
- **MCP 激活** — 提供方不接管已有的活动 Agent;被占用的附加连接不会在本次激活中重试。
|
|
83
|
+
- **附加范围** — 独占所有权作用于一个资源管理器,不约束独立提供方、进程或外部浏览器客户端。
|
|
84
|
+
- **取消** — abort 信号与连接关闭无法撤销已交付的浏览器操作。同时忽略两者的上游操作可能延迟清理。
|
|
85
|
+
- **恢复** — 关闭失败会保留所有权;此管理器不重试释放,也不从 Session 日志恢复浏览器状态。
|
|
86
|
+
|
|
87
|
+
<a id="dev-note"></a>
|
|
88
|
+
### 开发备注
|
|
89
|
+
|
|
90
|
+
<details>
|
|
91
|
+
<summary>维护者工作上下文 — 点击展开</summary>
|
|
92
|
+
|
|
93
|
+
无。
|
|
94
|
+
|
|
95
|
+
</details>
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
//#region lib/types/index.js
|
|
2
|
+
/**
|
|
3
|
+
* Browser resource ownership for the experimental providers. Resources belong
|
|
4
|
+
* to an exact live Agent activation and never transfer to a resumed Session.
|
|
5
|
+
* @module
|
|
6
|
+
*/
|
|
7
|
+
/** Stop a caller's wait while retaining handlers on the resource owner's work. */
|
|
8
|
+
function awaitOperation(operation, signal) {
|
|
9
|
+
return new Promise((resolve, reject) => {
|
|
10
|
+
const aborted = () => {
|
|
11
|
+
reject(signal.reason instanceof Error ? signal.reason : new Error("browser operation canceled", { cause: signal.reason }));
|
|
12
|
+
};
|
|
13
|
+
signal.addEventListener("abort", aborted, { once: true });
|
|
14
|
+
operation.then((value) => {
|
|
15
|
+
signal.removeEventListener("abort", aborted);
|
|
16
|
+
resolve(value);
|
|
17
|
+
}, (error) => {
|
|
18
|
+
signal.removeEventListener("abort", aborted);
|
|
19
|
+
reject(error instanceof Error ? error : new Error(String(error), { cause: error }));
|
|
20
|
+
});
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Lazily acquires one resource per live Session and serializes its operations.
|
|
25
|
+
* Provider disposal closes connections before awaiting operations, allowing
|
|
26
|
+
* transport closure to interrupt work whose upstream API has no abort support.
|
|
27
|
+
*/
|
|
28
|
+
var SessionResources = class {
|
|
29
|
+
ctx;
|
|
30
|
+
options;
|
|
31
|
+
entries = /* @__PURE__ */ new Map();
|
|
32
|
+
ownerCleanups = /* @__PURE__ */ new Map();
|
|
33
|
+
disposedOwners = /* @__PURE__ */ new WeakSet();
|
|
34
|
+
disposing;
|
|
35
|
+
/**
|
|
36
|
+
* @param ctx - provider context with the live Agent registry.
|
|
37
|
+
* @param options - provider-owned acquisition and attachment policy.
|
|
38
|
+
*/
|
|
39
|
+
constructor(ctx, options) {
|
|
40
|
+
this.ctx = ctx;
|
|
41
|
+
this.options = options;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Check admission without reserving or acquiring a browser.
|
|
45
|
+
* @param agent - exact live Agent that would own the resource.
|
|
46
|
+
* @returns whether this owner can use or acquire the configured browser.
|
|
47
|
+
*/
|
|
48
|
+
available(agent) {
|
|
49
|
+
return this.disposing === void 0 && !this.disposedOwners.has(agent) && this.ctx.get("agents")?.get(agent.id) === agent && (this.entries.has(agent) || !this.options.exclusive || this.entries.size === 0);
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Obtain the current activation's resource, acquiring it once when absent.
|
|
53
|
+
* @param agent - exact live owner, never merely a durable Session id.
|
|
54
|
+
* @param signal - optional cancellation of this wait; acquisition remains Session-owned.
|
|
55
|
+
* @returns the provider's resource after acquisition and ownership checks.
|
|
56
|
+
*/
|
|
57
|
+
async get(agent, signal) {
|
|
58
|
+
signal?.throwIfAborted();
|
|
59
|
+
const entry = this.entry(agent);
|
|
60
|
+
const resource = await (signal === void 0 ? entry.ready : awaitOperation(entry.ready, signal));
|
|
61
|
+
signal?.throwIfAborted();
|
|
62
|
+
entry.controller.signal.throwIfAborted();
|
|
63
|
+
return resource.value;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Run after earlier operations on this Session settle; other Sessions proceed independently.
|
|
67
|
+
* Cancellation stops this caller's acquisition wait without canceling Session-owned initialization.
|
|
68
|
+
* It reaches an active provider operation and prevents queued work from starting.
|
|
69
|
+
* @param agent - exact live resource owner.
|
|
70
|
+
* @param signal - cancellation for this operation.
|
|
71
|
+
* @param operation - provider call, which must retain ownership until its work settles.
|
|
72
|
+
* @returns the operation result or its acquisition, cancellation, or execution failure.
|
|
73
|
+
*/
|
|
74
|
+
run(agent, signal, operation) {
|
|
75
|
+
signal.throwIfAborted();
|
|
76
|
+
const entry = this.entry(agent);
|
|
77
|
+
const combined = AbortSignal.any([signal, entry.controller.signal]);
|
|
78
|
+
const releaseDisposed = () => {
|
|
79
|
+
if (signal.reason?.kind !== "disposed") return;
|
|
80
|
+
this.disposedOwners.add(agent);
|
|
81
|
+
this.closeEntry(agent, entry).catch((error) => {
|
|
82
|
+
this.ctx.logger.warn(`${this.options.label}: browser cleanup during Session cancellation failed: ${String(error)}`);
|
|
83
|
+
});
|
|
84
|
+
};
|
|
85
|
+
signal.addEventListener("abort", releaseDisposed, { once: true });
|
|
86
|
+
const task = entry.tail.then(async () => {
|
|
87
|
+
combined.throwIfAborted();
|
|
88
|
+
const resource = await awaitOperation(entry.ready, combined);
|
|
89
|
+
combined.throwIfAborted();
|
|
90
|
+
const result = await operation(resource.value, combined);
|
|
91
|
+
combined.throwIfAborted();
|
|
92
|
+
return result;
|
|
93
|
+
}).finally(() => {
|
|
94
|
+
signal.removeEventListener("abort", releaseDisposed);
|
|
95
|
+
});
|
|
96
|
+
entry.tail = task.then(() => {}, () => {});
|
|
97
|
+
return task;
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Stop new acquisitions and await every acquired resource and owned operation.
|
|
101
|
+
* A failed close retains its entry and rejects disposal, preserving exclusive ownership.
|
|
102
|
+
* @returns the shared quiescent disposal promise.
|
|
103
|
+
*/
|
|
104
|
+
dispose() {
|
|
105
|
+
return this.disposing ??= Promise.resolve().then(async () => {
|
|
106
|
+
const errors = (await Promise.allSettled([...this.entries].map(([agent, entry]) => this.closeEntry(agent, entry)))).flatMap((result) => result.status === "rejected" ? [result.reason] : []);
|
|
107
|
+
if (errors.length > 0) throw new AggregateError(errors, `${this.options.label}: browser cleanup failed`);
|
|
108
|
+
await Promise.all([...this.ownerCleanups.values()].map((close) => close()));
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
entry(agent) {
|
|
112
|
+
if (this.disposing !== void 0 || this.disposedOwners.has(agent) || this.ctx.get("agents")?.get(agent.id) !== agent) throw new Error(`${this.options.label}: Session is not a live browser owner`);
|
|
113
|
+
const current = this.entries.get(agent);
|
|
114
|
+
if (current !== void 0) return current;
|
|
115
|
+
if (this.options.exclusive && this.entries.size > 0) throw new Error(`${this.options.label}: attached browser is already reserved by another Session`);
|
|
116
|
+
if (!this.ownerCleanups.has(agent)) {
|
|
117
|
+
const cleanup = agent.ctx.effect(() => async () => {
|
|
118
|
+
this.disposedOwners.add(agent);
|
|
119
|
+
const owned = this.entries.get(agent);
|
|
120
|
+
if (owned !== void 0) await this.closeEntry(agent, owned);
|
|
121
|
+
this.ownerCleanups.delete(agent);
|
|
122
|
+
}, `${this.options.label}.session`);
|
|
123
|
+
this.ownerCleanups.set(agent, cleanup);
|
|
124
|
+
}
|
|
125
|
+
const controller = new AbortController();
|
|
126
|
+
const entry = {
|
|
127
|
+
controller,
|
|
128
|
+
ready: Promise.resolve().then(() => {
|
|
129
|
+
controller.signal.throwIfAborted();
|
|
130
|
+
return this.options.open(agent, controller.signal);
|
|
131
|
+
}).catch((error) => {
|
|
132
|
+
this.entries.delete(agent);
|
|
133
|
+
throw error;
|
|
134
|
+
}),
|
|
135
|
+
tail: Promise.resolve()
|
|
136
|
+
};
|
|
137
|
+
entry.ready.catch(() => {});
|
|
138
|
+
this.entries.set(agent, entry);
|
|
139
|
+
return entry;
|
|
140
|
+
}
|
|
141
|
+
closeEntry(agent, entry) {
|
|
142
|
+
return entry.closing ??= Promise.resolve().then(async () => {
|
|
143
|
+
entry.controller.abort(/* @__PURE__ */ new Error(`${this.options.label}: Session browser is closing`));
|
|
144
|
+
const resource = await entry.ready.catch(() => void 0);
|
|
145
|
+
try {
|
|
146
|
+
await resource?.close();
|
|
147
|
+
} finally {
|
|
148
|
+
await entry.tail;
|
|
149
|
+
}
|
|
150
|
+
this.entries.delete(agent);
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
//#endregion
|
|
155
|
+
export { SessionResources };
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Browser resource ownership for the experimental providers. Resources belong
|
|
3
|
+
* to an exact live Agent activation and never transfer to a resumed Session.
|
|
4
|
+
* @module
|
|
5
|
+
*/
|
|
6
|
+
import type { Context } from '@qilin-agent/kylin';
|
|
7
|
+
import type { Agent } from '@qilin-agent/agent';
|
|
8
|
+
/** One provider-owned browser or connection and its quiescent cleanup. */
|
|
9
|
+
export interface OwnedSessionResource<T> {
|
|
10
|
+
/** Provider-private handle exposed to operations. */
|
|
11
|
+
value: T;
|
|
12
|
+
/** Stop admission, interrupt pending operations, and await resource shutdown. */
|
|
13
|
+
close: () => Promise<void>;
|
|
14
|
+
}
|
|
15
|
+
/** Resource creation and attachment ownership selected by one provider. */
|
|
16
|
+
export interface SessionResourceOptions<T> {
|
|
17
|
+
/** Provider name included in lifecycle diagnostics. */
|
|
18
|
+
label: string;
|
|
19
|
+
/** Reserve one existing browser for at most one live Session. */
|
|
20
|
+
exclusive: boolean;
|
|
21
|
+
/**
|
|
22
|
+
* Acquire one resource; reject only after rolling back partial acquisition.
|
|
23
|
+
* @param agent - exact live owner of this acquisition.
|
|
24
|
+
* @param signal - aborts when that owner or the provider is disposed.
|
|
25
|
+
* @returns the acquired resource and its cleanup.
|
|
26
|
+
*/
|
|
27
|
+
open: (agent: Agent, signal: AbortSignal) => Promise<OwnedSessionResource<T>>;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Lazily acquires one resource per live Session and serializes its operations.
|
|
31
|
+
* Provider disposal closes connections before awaiting operations, allowing
|
|
32
|
+
* transport closure to interrupt work whose upstream API has no abort support.
|
|
33
|
+
*/
|
|
34
|
+
export declare class SessionResources<T> {
|
|
35
|
+
private readonly ctx;
|
|
36
|
+
private readonly options;
|
|
37
|
+
private readonly entries;
|
|
38
|
+
private readonly ownerCleanups;
|
|
39
|
+
private readonly disposedOwners;
|
|
40
|
+
private disposing;
|
|
41
|
+
/**
|
|
42
|
+
* @param ctx - provider context with the live Agent registry.
|
|
43
|
+
* @param options - provider-owned acquisition and attachment policy.
|
|
44
|
+
*/
|
|
45
|
+
constructor(ctx: Context, options: SessionResourceOptions<T>);
|
|
46
|
+
/**
|
|
47
|
+
* Check admission without reserving or acquiring a browser.
|
|
48
|
+
* @param agent - exact live Agent that would own the resource.
|
|
49
|
+
* @returns whether this owner can use or acquire the configured browser.
|
|
50
|
+
*/
|
|
51
|
+
available(agent: Agent): boolean;
|
|
52
|
+
/**
|
|
53
|
+
* Obtain the current activation's resource, acquiring it once when absent.
|
|
54
|
+
* @param agent - exact live owner, never merely a durable Session id.
|
|
55
|
+
* @param signal - optional cancellation of this wait; acquisition remains Session-owned.
|
|
56
|
+
* @returns the provider's resource after acquisition and ownership checks.
|
|
57
|
+
*/
|
|
58
|
+
get(agent: Agent, signal?: AbortSignal): Promise<T>;
|
|
59
|
+
/**
|
|
60
|
+
* Run after earlier operations on this Session settle; other Sessions proceed independently.
|
|
61
|
+
* Cancellation stops this caller's acquisition wait without canceling Session-owned initialization.
|
|
62
|
+
* It reaches an active provider operation and prevents queued work from starting.
|
|
63
|
+
* @param agent - exact live resource owner.
|
|
64
|
+
* @param signal - cancellation for this operation.
|
|
65
|
+
* @param operation - provider call, which must retain ownership until its work settles.
|
|
66
|
+
* @returns the operation result or its acquisition, cancellation, or execution failure.
|
|
67
|
+
*/
|
|
68
|
+
run<R>(agent: Agent, signal: AbortSignal, operation: (resource: T, signal: AbortSignal) => Promise<R>): Promise<R>;
|
|
69
|
+
/**
|
|
70
|
+
* Stop new acquisitions and await every acquired resource and owned operation.
|
|
71
|
+
* A failed close retains its entry and rejects disposal, preserving exclusive ownership.
|
|
72
|
+
* @returns the shared quiescent disposal promise.
|
|
73
|
+
*/
|
|
74
|
+
dispose(): Promise<void>;
|
|
75
|
+
private entry;
|
|
76
|
+
private closeEntry;
|
|
77
|
+
}
|
|
78
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Browser resource ownership for the experimental providers. Resources belong
|
|
3
|
+
* to an exact live Agent activation and never transfer to a resumed Session.
|
|
4
|
+
* @module
|
|
5
|
+
*/
|
|
6
|
+
/** Stop a caller's wait while retaining handlers on the resource owner's work. */
|
|
7
|
+
function awaitOperation(operation, signal) {
|
|
8
|
+
return new Promise((resolve, reject) => {
|
|
9
|
+
const aborted = () => { reject(signal.reason instanceof Error ? signal.reason : new Error('browser operation canceled', { cause: signal.reason })); };
|
|
10
|
+
signal.addEventListener('abort', aborted, { once: true });
|
|
11
|
+
void operation.then((value) => {
|
|
12
|
+
signal.removeEventListener('abort', aborted);
|
|
13
|
+
resolve(value);
|
|
14
|
+
}, (error) => {
|
|
15
|
+
signal.removeEventListener('abort', aborted);
|
|
16
|
+
reject(error instanceof Error ? error : new Error(String(error), { cause: error }));
|
|
17
|
+
});
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Lazily acquires one resource per live Session and serializes its operations.
|
|
22
|
+
* Provider disposal closes connections before awaiting operations, allowing
|
|
23
|
+
* transport closure to interrupt work whose upstream API has no abort support.
|
|
24
|
+
*/
|
|
25
|
+
export class SessionResources {
|
|
26
|
+
ctx;
|
|
27
|
+
options;
|
|
28
|
+
entries = new Map();
|
|
29
|
+
ownerCleanups = new Map();
|
|
30
|
+
disposedOwners = new WeakSet();
|
|
31
|
+
disposing;
|
|
32
|
+
/**
|
|
33
|
+
* @param ctx - provider context with the live Agent registry.
|
|
34
|
+
* @param options - provider-owned acquisition and attachment policy.
|
|
35
|
+
*/
|
|
36
|
+
constructor(ctx, options) {
|
|
37
|
+
this.ctx = ctx;
|
|
38
|
+
this.options = options;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Check admission without reserving or acquiring a browser.
|
|
42
|
+
* @param agent - exact live Agent that would own the resource.
|
|
43
|
+
* @returns whether this owner can use or acquire the configured browser.
|
|
44
|
+
*/
|
|
45
|
+
available(agent) {
|
|
46
|
+
return this.disposing === undefined && !this.disposedOwners.has(agent)
|
|
47
|
+
&& this.ctx.get('agents')?.get(agent.id) === agent
|
|
48
|
+
&& (this.entries.has(agent) || !this.options.exclusive || this.entries.size === 0);
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Obtain the current activation's resource, acquiring it once when absent.
|
|
52
|
+
* @param agent - exact live owner, never merely a durable Session id.
|
|
53
|
+
* @param signal - optional cancellation of this wait; acquisition remains Session-owned.
|
|
54
|
+
* @returns the provider's resource after acquisition and ownership checks.
|
|
55
|
+
*/
|
|
56
|
+
async get(agent, signal) {
|
|
57
|
+
signal?.throwIfAborted();
|
|
58
|
+
const entry = this.entry(agent);
|
|
59
|
+
const resource = await (signal === undefined ? entry.ready : awaitOperation(entry.ready, signal));
|
|
60
|
+
signal?.throwIfAborted();
|
|
61
|
+
entry.controller.signal.throwIfAborted();
|
|
62
|
+
return resource.value;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Run after earlier operations on this Session settle; other Sessions proceed independently.
|
|
66
|
+
* Cancellation stops this caller's acquisition wait without canceling Session-owned initialization.
|
|
67
|
+
* It reaches an active provider operation and prevents queued work from starting.
|
|
68
|
+
* @param agent - exact live resource owner.
|
|
69
|
+
* @param signal - cancellation for this operation.
|
|
70
|
+
* @param operation - provider call, which must retain ownership until its work settles.
|
|
71
|
+
* @returns the operation result or its acquisition, cancellation, or execution failure.
|
|
72
|
+
*/
|
|
73
|
+
run(agent, signal, operation) {
|
|
74
|
+
signal.throwIfAborted();
|
|
75
|
+
const entry = this.entry(agent);
|
|
76
|
+
const combined = AbortSignal.any([signal, entry.controller.signal]);
|
|
77
|
+
const releaseDisposed = () => {
|
|
78
|
+
const reason = signal.reason;
|
|
79
|
+
if (reason?.kind !== 'disposed')
|
|
80
|
+
return;
|
|
81
|
+
this.disposedOwners.add(agent);
|
|
82
|
+
// AgentHandle waits for idle before disposing its scope; close interrupts the owned operation first.
|
|
83
|
+
void this.closeEntry(agent, entry).catch((error) => {
|
|
84
|
+
this.ctx.logger.warn(`${this.options.label}: browser cleanup during Session cancellation failed: ${String(error)}`);
|
|
85
|
+
});
|
|
86
|
+
};
|
|
87
|
+
signal.addEventListener('abort', releaseDisposed, { once: true });
|
|
88
|
+
const task = entry.tail.then(async () => {
|
|
89
|
+
combined.throwIfAborted();
|
|
90
|
+
const resource = await awaitOperation(entry.ready, combined);
|
|
91
|
+
combined.throwIfAborted();
|
|
92
|
+
const result = await operation(resource.value, combined);
|
|
93
|
+
combined.throwIfAborted();
|
|
94
|
+
return result;
|
|
95
|
+
}).finally(() => { signal.removeEventListener('abort', releaseDisposed); });
|
|
96
|
+
// The queue tracks settlement independently of a caller observing its error.
|
|
97
|
+
entry.tail = task.then(() => { }, () => { });
|
|
98
|
+
return task;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Stop new acquisitions and await every acquired resource and owned operation.
|
|
102
|
+
* A failed close retains its entry and rejects disposal, preserving exclusive ownership.
|
|
103
|
+
* @returns the shared quiescent disposal promise.
|
|
104
|
+
*/
|
|
105
|
+
dispose() {
|
|
106
|
+
return this.disposing ??= Promise.resolve().then(async () => {
|
|
107
|
+
const settled = await Promise.allSettled([...this.entries].map(([agent, entry]) => this.closeEntry(agent, entry)));
|
|
108
|
+
const errors = settled.flatMap(result => result.status === 'rejected' ? [result.reason] : []);
|
|
109
|
+
if (errors.length > 0)
|
|
110
|
+
throw new AggregateError(errors, `${this.options.label}: browser cleanup failed`);
|
|
111
|
+
await Promise.all([...this.ownerCleanups.values()].map(close => close()));
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
entry(agent) {
|
|
115
|
+
if (this.disposing !== undefined || this.disposedOwners.has(agent) || this.ctx.get('agents')?.get(agent.id) !== agent) {
|
|
116
|
+
throw new Error(`${this.options.label}: Session is not a live browser owner`);
|
|
117
|
+
}
|
|
118
|
+
const current = this.entries.get(agent);
|
|
119
|
+
if (current !== undefined)
|
|
120
|
+
return current;
|
|
121
|
+
if (this.options.exclusive && this.entries.size > 0) {
|
|
122
|
+
throw new Error(`${this.options.label}: attached browser is already reserved by another Session`);
|
|
123
|
+
}
|
|
124
|
+
if (!this.ownerCleanups.has(agent)) {
|
|
125
|
+
const cleanup = agent.ctx.effect(() => async () => {
|
|
126
|
+
this.disposedOwners.add(agent);
|
|
127
|
+
const owned = this.entries.get(agent);
|
|
128
|
+
if (owned !== undefined)
|
|
129
|
+
await this.closeEntry(agent, owned);
|
|
130
|
+
this.ownerCleanups.delete(agent);
|
|
131
|
+
}, `${this.options.label}.session`);
|
|
132
|
+
this.ownerCleanups.set(agent, cleanup);
|
|
133
|
+
}
|
|
134
|
+
const controller = new AbortController();
|
|
135
|
+
const entry = {
|
|
136
|
+
controller,
|
|
137
|
+
ready: Promise.resolve().then(() => {
|
|
138
|
+
controller.signal.throwIfAborted();
|
|
139
|
+
return this.options.open(agent, controller.signal);
|
|
140
|
+
}).catch((error) => {
|
|
141
|
+
// open() owns rollback; a failed acquisition has no remaining resource.
|
|
142
|
+
this.entries.delete(agent);
|
|
143
|
+
throw error;
|
|
144
|
+
}),
|
|
145
|
+
tail: Promise.resolve(),
|
|
146
|
+
};
|
|
147
|
+
// Acquisition can outlive every canceled caller; later consumers still receive its failure.
|
|
148
|
+
void entry.ready.catch(() => { });
|
|
149
|
+
this.entries.set(agent, entry);
|
|
150
|
+
return entry;
|
|
151
|
+
}
|
|
152
|
+
closeEntry(agent, entry) {
|
|
153
|
+
return entry.closing ??= Promise.resolve().then(async () => {
|
|
154
|
+
entry.controller.abort(new Error(`${this.options.label}: Session browser is closing`));
|
|
155
|
+
const resource = await entry.ready.catch(() => undefined);
|
|
156
|
+
try {
|
|
157
|
+
await resource?.close();
|
|
158
|
+
}
|
|
159
|
+
finally {
|
|
160
|
+
await entry.tail;
|
|
161
|
+
}
|
|
162
|
+
this.entries.delete(agent);
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/** Session-owned MCP browser processes and provider catalog activation. @module */
|
|
2
|
+
import type { Context } from '@qilin-agent/kylin';
|
|
3
|
+
import Schema from '@qilin-agent/schemastery';
|
|
4
|
+
/** Browser launch settings shared by the MCP integrations. */
|
|
5
|
+
export interface BrowserMcpLaunchConfig {
|
|
6
|
+
/** Launch a new isolated Chromium browser for each live Session. */
|
|
7
|
+
mode: 'launch';
|
|
8
|
+
/** Whether Chromium runs without a visible window; defaults to true. */
|
|
9
|
+
headless: boolean;
|
|
10
|
+
/** Chromium executable; omission uses the upstream server's installation discovery. */
|
|
11
|
+
executablePath?: string;
|
|
12
|
+
/** Per-call timeout override in milliseconds; omission uses the MCP client default. */
|
|
13
|
+
toolCallTimeoutMs?: number;
|
|
14
|
+
}
|
|
15
|
+
/** Attachment to an externally owned Chromium browser. */
|
|
16
|
+
export interface BrowserMcpAttachConfig {
|
|
17
|
+
/** Exclusively attach one live Session to the configured browser. */
|
|
18
|
+
mode: 'attach';
|
|
19
|
+
/** HTTP(S) debugging URL or WS(S) browser debugging endpoint. */
|
|
20
|
+
endpoint: string;
|
|
21
|
+
/** Per-call timeout override in milliseconds; omission uses the MCP client default. */
|
|
22
|
+
toolCallTimeoutMs?: number;
|
|
23
|
+
}
|
|
24
|
+
/** Fixed launch or attachment choice for one MCP browser provider. */
|
|
25
|
+
export type BrowserMcpConfig = BrowserMcpLaunchConfig | BrowserMcpAttachConfig;
|
|
26
|
+
/** Validate the browser mode before the provider reserves browser use. */
|
|
27
|
+
export declare const BrowserMcpConfig: Schema<BrowserMcpAttachConfig | (Omit<BrowserMcpLaunchConfig, 'headless'> & {
|
|
28
|
+
headless?: boolean;
|
|
29
|
+
}), BrowserMcpConfig>;
|
|
30
|
+
/**
|
|
31
|
+
* Reject an invalid debugging endpoint before acquiring provider or browser resources.
|
|
32
|
+
* @param config - schema-validated browser selection.
|
|
33
|
+
*/
|
|
34
|
+
export declare function validateBrowserMcpConfig(config: BrowserMcpConfig): void;
|
|
35
|
+
/** Provider-owned connection options for one live Session. */
|
|
36
|
+
export interface SessionMcpOptions {
|
|
37
|
+
/** Provider identity and MCP tool namespace. */
|
|
38
|
+
name: string;
|
|
39
|
+
/** Whether another live Session must wait for the attached browser to be released. */
|
|
40
|
+
exclusive: boolean;
|
|
41
|
+
/** Executable used to start the installed MCP server. */
|
|
42
|
+
command: string;
|
|
43
|
+
/** Arguments passed directly without a shell. */
|
|
44
|
+
args: string[];
|
|
45
|
+
/** Explicit overrides merged into the MCP client's scrubbed child environment. */
|
|
46
|
+
env?: Record<string, string>;
|
|
47
|
+
/** Per-call timeout override; omission retains the MCP client default. */
|
|
48
|
+
toolCallTimeoutMs?: number;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Await one MCP client during each future Agent's creation.
|
|
52
|
+
* A busy attachment leaves that activation without browser tools; its other turns continue.
|
|
53
|
+
* Calls are serialized per Session; unload closes every server before releasing registration.
|
|
54
|
+
* @param ctx - provider context supplying browser use, Agents, tools, and prompt assembly.
|
|
55
|
+
* @param options - provider identity, attachment exclusivity, and executable configuration.
|
|
56
|
+
*/
|
|
57
|
+
export declare function mountSessionMcp(ctx: Context, options: SessionMcpOptions): void;
|
|
58
|
+
//# sourceMappingURL=mcp.d.ts.map
|
package/lib/types/mcp.js
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
/** Session-owned MCP browser processes and provider catalog activation. @module */
|
|
2
|
+
import Schema from '@qilin-agent/schemastery';
|
|
3
|
+
import { BrowserUseProviderName } from '@qilin-agent/browser-use/brand';
|
|
4
|
+
import * as McpClient from '@qilin-agent/mcp-client';
|
|
5
|
+
import { createScope } from '@qilin-agent/scope';
|
|
6
|
+
import { SessionResources } from "./index.js";
|
|
7
|
+
/** Validate the browser mode before the provider reserves browser use. */
|
|
8
|
+
export const BrowserMcpConfig = Schema.union([
|
|
9
|
+
Schema.object({
|
|
10
|
+
mode: Schema.const('launch').required(),
|
|
11
|
+
headless: Schema.boolean().default(true),
|
|
12
|
+
executablePath: Schema.string().pattern(/\S/u),
|
|
13
|
+
toolCallTimeoutMs: Schema.number().min(1),
|
|
14
|
+
}),
|
|
15
|
+
Schema.object({
|
|
16
|
+
mode: Schema.const('attach').required(),
|
|
17
|
+
endpoint: Schema.string().pattern(/^https?:\/\/[^\s/]+|^wss?:\/\/[^\s/]+/u).required(),
|
|
18
|
+
toolCallTimeoutMs: Schema.number().min(1),
|
|
19
|
+
}),
|
|
20
|
+
]);
|
|
21
|
+
/**
|
|
22
|
+
* Reject an invalid debugging endpoint before acquiring provider or browser resources.
|
|
23
|
+
* @param config - schema-validated browser selection.
|
|
24
|
+
*/
|
|
25
|
+
export function validateBrowserMcpConfig(config) {
|
|
26
|
+
if (config.mode !== 'attach')
|
|
27
|
+
return;
|
|
28
|
+
let endpoint;
|
|
29
|
+
try {
|
|
30
|
+
endpoint = new URL(config.endpoint);
|
|
31
|
+
}
|
|
32
|
+
catch (error) {
|
|
33
|
+
throw new Error('browser endpoint must be a valid HTTP(S) or WS(S) URL', { cause: error });
|
|
34
|
+
}
|
|
35
|
+
if (!['http:', 'https:', 'ws:', 'wss:'].includes(endpoint.protocol) || /\s/u.test(config.endpoint)) {
|
|
36
|
+
throw new Error('browser endpoint must be a valid HTTP(S) or WS(S) URL without whitespace');
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Await one MCP client during each future Agent's creation.
|
|
41
|
+
* A busy attachment leaves that activation without browser tools; its other turns continue.
|
|
42
|
+
* Calls are serialized per Session; unload closes every server before releasing registration.
|
|
43
|
+
* @param ctx - provider context supplying browser use, Agents, tools, and prompt assembly.
|
|
44
|
+
* @param options - provider identity, attachment exclusivity, and executable configuration.
|
|
45
|
+
*/
|
|
46
|
+
export function mountSessionMcp(ctx, options) {
|
|
47
|
+
let resources;
|
|
48
|
+
const clients = new Map();
|
|
49
|
+
const toolPrefix = `mcp__${options.name}__`;
|
|
50
|
+
const resourceTools = new Set(['list_mcp_resources', 'list_mcp_resource_templates', 'read_mcp_resource']);
|
|
51
|
+
let stopping = false;
|
|
52
|
+
let refreshingMasks = false;
|
|
53
|
+
const refreshBlockedMasks = () => {
|
|
54
|
+
if (stopping || refreshingMasks)
|
|
55
|
+
return;
|
|
56
|
+
refreshingMasks = true;
|
|
57
|
+
try {
|
|
58
|
+
for (const [agent, state] of clients) {
|
|
59
|
+
if (state.status !== 'blocked')
|
|
60
|
+
continue;
|
|
61
|
+
const inherited = ctx.tools.schemas(agent).filter(tool => tool.name.startsWith(toolPrefix));
|
|
62
|
+
if (inherited.length === 0)
|
|
63
|
+
continue;
|
|
64
|
+
state.mask ??= createScope(ctx, agent);
|
|
65
|
+
state.mask.ctx.tools.restrict({ deny: inherited.map(tool => tool.name) });
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
finally {
|
|
69
|
+
refreshingMasks = false;
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
ctx.effect(function* () {
|
|
73
|
+
yield ctx.browserUse.register(BrowserUseProviderName(options.name));
|
|
74
|
+
resources = new SessionResources(ctx, {
|
|
75
|
+
label: options.name,
|
|
76
|
+
exclusive: options.exclusive,
|
|
77
|
+
async open(agent, signal) {
|
|
78
|
+
const scope = createScope(ctx, agent);
|
|
79
|
+
let cancellation;
|
|
80
|
+
const cancel = () => { cancellation = scope.dispose(); };
|
|
81
|
+
signal.addEventListener('abort', cancel, { once: true });
|
|
82
|
+
try {
|
|
83
|
+
signal.throwIfAborted();
|
|
84
|
+
scope.ctx.on('tools/execute', async (exec, next) => {
|
|
85
|
+
if (!exec.name.startsWith(toolPrefix))
|
|
86
|
+
return next();
|
|
87
|
+
if (exec.agent !== agent) {
|
|
88
|
+
if (ctx.tools.get(exec.name, exec.agent) !== ctx.tools.get(exec.name, agent))
|
|
89
|
+
return next();
|
|
90
|
+
throw new Error(`${options.name}: browser tool belongs to another Session`);
|
|
91
|
+
}
|
|
92
|
+
return next();
|
|
93
|
+
});
|
|
94
|
+
await scope.ctx.plugin(McpClient, McpClient.Config({
|
|
95
|
+
transport: 'stdio',
|
|
96
|
+
serverName: options.name,
|
|
97
|
+
command: options.command,
|
|
98
|
+
args: options.args,
|
|
99
|
+
...options.env === undefined ? {} : { env: options.env },
|
|
100
|
+
...agent.session.header.cwd === undefined ? {} : { cwd: agent.session.header.cwd },
|
|
101
|
+
...options.toolCallTimeoutMs === undefined ? {} : { toolCallTimeoutMs: options.toolCallTimeoutMs },
|
|
102
|
+
failOnStartupError: true,
|
|
103
|
+
reconnect: { enabled: false },
|
|
104
|
+
}));
|
|
105
|
+
signal.throwIfAborted();
|
|
106
|
+
return {
|
|
107
|
+
value: scope,
|
|
108
|
+
close() {
|
|
109
|
+
clients.delete(agent);
|
|
110
|
+
return scope.dispose();
|
|
111
|
+
},
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
catch (error) {
|
|
115
|
+
await (cancellation ?? scope.dispose());
|
|
116
|
+
throw error;
|
|
117
|
+
}
|
|
118
|
+
finally {
|
|
119
|
+
signal.removeEventListener('abort', cancel);
|
|
120
|
+
}
|
|
121
|
+
},
|
|
122
|
+
});
|
|
123
|
+
yield async () => {
|
|
124
|
+
stopping = true;
|
|
125
|
+
await resources.dispose();
|
|
126
|
+
clients.clear();
|
|
127
|
+
};
|
|
128
|
+
}, `${options.name}.sessions`);
|
|
129
|
+
ctx.on('agent/created', async ({ agent, signal }) => {
|
|
130
|
+
const state = { status: resources.available(agent) ? 'ready' : 'blocked' };
|
|
131
|
+
agent.ctx.effect(() => async () => {
|
|
132
|
+
clients.delete(agent);
|
|
133
|
+
await state.mask?.dispose();
|
|
134
|
+
}, `${options.name}.activation`);
|
|
135
|
+
if (state.status === 'blocked') {
|
|
136
|
+
clients.set(agent, state);
|
|
137
|
+
refreshBlockedMasks();
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
await resources.get(agent, signal);
|
|
141
|
+
clients.set(agent, state);
|
|
142
|
+
}, { prepend: true });
|
|
143
|
+
ctx.on('tools/change', refreshBlockedMasks);
|
|
144
|
+
ctx.on('tools/execute', async (exec, next) => {
|
|
145
|
+
const ownResource = resourceTools.has(exec.name)
|
|
146
|
+
&& typeof exec.arguments === 'object' && exec.arguments !== null
|
|
147
|
+
&& exec.arguments.server === options.name;
|
|
148
|
+
if (!exec.name.startsWith(toolPrefix) && !ownResource)
|
|
149
|
+
return next();
|
|
150
|
+
const agent = exec.agent;
|
|
151
|
+
if (agent === undefined || clients.get(agent)?.status !== 'ready') {
|
|
152
|
+
throw new Error(`${options.name}: browser tool belongs to another Session`);
|
|
153
|
+
}
|
|
154
|
+
return resources.run(agent, exec.signal, async (_scope, combined) => {
|
|
155
|
+
const original = exec.signal;
|
|
156
|
+
exec.signal = combined;
|
|
157
|
+
try {
|
|
158
|
+
return await next();
|
|
159
|
+
}
|
|
160
|
+
finally {
|
|
161
|
+
exec.signal = original;
|
|
162
|
+
}
|
|
163
|
+
});
|
|
164
|
+
});
|
|
165
|
+
ctx.on('system-prompt/assemble', async (_assembly, { agent }, next) => {
|
|
166
|
+
const assembly = await next();
|
|
167
|
+
if (agent === undefined || clients.get(agent)?.status === 'ready')
|
|
168
|
+
return assembly;
|
|
169
|
+
return { ...assembly, sections: assembly.sections.filter(section => section.name !== `mcp:${options.name}`) };
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
//# sourceMappingURL=mcp.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,67 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@qilin-agent/experimental-browser-use-runtime",
|
|
3
|
-
"
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"description": "Session-owned browser resource lifecycles and MCP integration for experimental providers",
|
|
4
|
+
"version": "3.1.4",
|
|
5
|
+
"publishConfig": {
|
|
6
|
+
"access": "public"
|
|
7
|
+
},
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/kkutysllb/QiLin.git",
|
|
11
|
+
"directory": "packages/experimental/browser-use-runtime"
|
|
12
|
+
},
|
|
13
|
+
"engines": {
|
|
14
|
+
"node": "^22.19.0 || >=24.0.0"
|
|
15
|
+
},
|
|
16
|
+
"type": "module",
|
|
17
|
+
"main": "lib/index.js",
|
|
18
|
+
"types": "lib/types/index.d.ts",
|
|
19
|
+
"exports": {
|
|
20
|
+
".": {
|
|
21
|
+
"types": "./lib/types/index.d.ts",
|
|
22
|
+
"default": "./lib/index.js"
|
|
23
|
+
},
|
|
24
|
+
"./src/*": "./src/*",
|
|
25
|
+
"./package.json": "./package.json",
|
|
26
|
+
"./mcp": {
|
|
27
|
+
"types": "./lib/types/mcp.d.ts",
|
|
28
|
+
"default": "./lib/types/mcp.js"
|
|
29
|
+
}
|
|
30
|
+
},
|
|
31
|
+
"files": [
|
|
32
|
+
"lib/index.js",
|
|
33
|
+
"lib/types/**/*.js",
|
|
34
|
+
"lib/types/**/*.d.ts"
|
|
35
|
+
],
|
|
36
|
+
"license": "MIT",
|
|
37
|
+
"peerDependencies": {
|
|
38
|
+
"@qilin-agent/kylin": "~4.0.3",
|
|
39
|
+
"@qilin-agent/agent": "3.1.4",
|
|
40
|
+
"@qilin-agent/browser-use": "3.1.4",
|
|
41
|
+
"@qilin-agent/tools": "3.1.4",
|
|
42
|
+
"@qilin-agent/system-prompt": "3.1.4"
|
|
43
|
+
},
|
|
44
|
+
"dependencies": {
|
|
45
|
+
"@qilin-agent/scope": "3.1.4",
|
|
46
|
+
"@qilin-agent/mcp-client": "3.1.4",
|
|
47
|
+
"@qilin-agent/schemastery": "~3.18.3"
|
|
48
|
+
},
|
|
49
|
+
"devDependencies": {
|
|
50
|
+
"@qilin-agent/kylin": "~4.0.3",
|
|
51
|
+
"@qilin-agent/agent": "3.1.4",
|
|
52
|
+
"@qilin-agent/browser-use": "3.1.4",
|
|
53
|
+
"@qilin-agent/tools": "3.1.4",
|
|
54
|
+
"@qilin-agent/agent-loop-testkit": "3.1.4",
|
|
55
|
+
"@qilin-agent/agent-loop": "3.1.4",
|
|
56
|
+
"@qilin-agent/session": "3.1.4",
|
|
57
|
+
"@qilin-agent/session-projection": "3.1.4",
|
|
58
|
+
"@qilin-agent/mcp-resources": "3.1.4",
|
|
59
|
+
"@qilin-agent/ptc-runtime": "3.1.4",
|
|
60
|
+
"@qilin-agent/system-prompt": "3.1.4",
|
|
61
|
+
"@qilin-agent/llm": "3.1.4",
|
|
62
|
+
"@qilin-agent/kylin-plugin-loader": "~1.0.4",
|
|
63
|
+
"@qilin-agent/kylin-plugin-include": "~1.0.8",
|
|
64
|
+
"@qilin-agent/attachment-local": "3.1.4",
|
|
65
|
+
"@qilin-agent/session-persistence-jsonl": "3.1.4"
|
|
66
|
+
}
|
|
6
67
|
}
|