@x-otto/shared 0.1.0-alpha.0 → 0.1.0-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -10
- package/dist/index.d.ts +12 -26
- package/dist/index.js +2 -2
- package/package.json +10 -10
package/README.md
CHANGED
|
@@ -1,23 +1,23 @@
|
|
|
1
|
-
# @otto/shared
|
|
1
|
+
# @x-otto/shared
|
|
2
2
|
|
|
3
3
|
> General infrastructure toolkit: error system, structured logging, event emitters, HTTP/SSE client, JSONC, file system utilities, OAuth primitives, fuzzy search, text truncation, and more.
|
|
4
4
|
|
|
5
|
-
`@otto/shared` provides the shared utilities consumed by most packages in the monorepo. It depends on `@otto/env` and adds pino for structured logging, undici for HTTP, and a comprehensive error hierarchy with 11 domain-specific error classes. It also exposes a browser-safe entry point (`@otto/shared/browser`) with event primitives only.
|
|
5
|
+
`@x-otto/shared` provides the shared utilities consumed by most packages in the monorepo. It depends on `@x-otto/env` and adds pino for structured logging, undici for HTTP, and a comprehensive error hierarchy with 11 domain-specific error classes. It also exposes a browser-safe entry point (`@x-otto/shared/browser`) with event primitives only.
|
|
6
6
|
|
|
7
7
|
## Installation
|
|
8
8
|
|
|
9
9
|
```bash
|
|
10
|
-
pnpm add @otto/shared
|
|
10
|
+
pnpm add @x-otto/shared
|
|
11
11
|
```
|
|
12
12
|
|
|
13
13
|
## Usage
|
|
14
14
|
|
|
15
15
|
```ts
|
|
16
|
-
import { createLogger } from '@otto/shared'
|
|
17
|
-
import { CodedError, NetworkError } from '@otto/shared'
|
|
18
|
-
import { TypedEventEmitter } from '@otto/shared'
|
|
19
|
-
import { parseJsonc, safeStringify } from '@otto/shared'
|
|
20
|
-
import { request, stream } from '@otto/shared'
|
|
16
|
+
import { createLogger } from '@x-otto/shared'
|
|
17
|
+
import { CodedError, NetworkError } from '@x-otto/shared'
|
|
18
|
+
import { TypedEventEmitter } from '@x-otto/shared'
|
|
19
|
+
import { parseJsonc, safeStringify } from '@x-otto/shared'
|
|
20
|
+
import { request, stream } from '@x-otto/shared'
|
|
21
21
|
|
|
22
22
|
// Logging
|
|
23
23
|
const log = createLogger('my-module')
|
|
@@ -90,7 +90,7 @@ for await (const event of stream('https://api.example.com/stream')) {
|
|
|
90
90
|
- `rankCandidates(query, items)` / `rankNamedItems(query, items)` — ranked search
|
|
91
91
|
|
|
92
92
|
### Other
|
|
93
|
-
- `invariant(condition, message)` — type-narrowing assertion (merged from `@otto/invariant`, RFC-157 M3a)
|
|
93
|
+
- `invariant(condition, message)` — type-narrowing assertion (merged from `@x-otto/invariant`, RFC-157 M3a)
|
|
94
94
|
- `splitFrontmatter(text)` / `parseFrontmatterFields(text)` — frontmatter parsing
|
|
95
95
|
- `probeImageDimensions(data)` — image dimension extraction
|
|
96
96
|
- `checkShellCommand(cmd)` / `buildAllowedEnv()` — command validation
|
|
@@ -99,7 +99,7 @@ for await (const event of stream('https://api.example.com/stream')) {
|
|
|
99
99
|
|
|
100
100
|
## Dependencies
|
|
101
101
|
|
|
102
|
-
- Internal: `@otto/env`
|
|
102
|
+
- Internal: `@x-otto/env`
|
|
103
103
|
- External: `pino`, `pino-pretty`, `eventsource-parser`, `jsonc-parser`, `mime-types`, `safe-stable-stringify`, `uuid`, `undici`
|
|
104
104
|
|
|
105
105
|
## Related
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { i as TypedEventEmitter, n as EventListener, r as Events, t as EventBus } from "./event-bus-inioRzYz.js";
|
|
2
2
|
import pino, { Logger } from "pino";
|
|
3
|
+
import { normalizePath } from "@x-otto/env";
|
|
3
4
|
import { ProxyAgent } from "undici";
|
|
4
5
|
|
|
5
6
|
//#region src/error.d.ts
|
|
@@ -86,7 +87,7 @@ declare function createLogger(name: string, options?: LoggerOptions): pino.Logge
|
|
|
86
87
|
/**
|
|
87
88
|
* 大文件字节阈值单一权威定义(RFC-189 D2,grill 已确认 10MB):文件"用户主动打开任意
|
|
88
89
|
* 文件系统路径查看"场景(`/open` 命令、`@file` sigil 预览)的读取层与渲染层
|
|
89
|
-
* (`@otto/tui file-content-views.ts` 的候选视图熔断)共用同一个数字,避免两处各自
|
|
90
|
+
* (`@x-otto/tui file-content-views.ts` 的候选视图熔断)共用同一个数字,避免两处各自
|
|
90
91
|
* 定义产生不一致(如读取层限 10MB、渲染层限 8MB)。
|
|
91
92
|
*/
|
|
92
93
|
declare const LARGE_FILE_BYTE_THRESHOLD: number;
|
|
@@ -157,21 +158,6 @@ declare function truncateLine(line: string, maxChars: number): {
|
|
|
157
158
|
wasTruncated: boolean;
|
|
158
159
|
};
|
|
159
160
|
//#endregion
|
|
160
|
-
//#region ../env/dist/index.d.ts
|
|
161
|
-
declare function normalizePath(path: string): string;
|
|
162
|
-
/**
|
|
163
|
-
* 从 `startDir` 向上查找最近的 `pnpm-workspace.yaml`(monorepo root 标志文件),返回其所在目录。
|
|
164
|
-
* 找不到(如在非本仓的用户项目里运行)返回 `undefined`。
|
|
165
|
-
*
|
|
166
|
-
* RFC-130:单一真源实现——原先在 `@otto/coding`(`install-plugin.ts`,供 CLI `--repo` 消费)与
|
|
167
|
-
* `@otto/plugin`(`discovery.ts`,供仓库级插件发现消费)各自维护一份逐字相同的实现(copy-paste),
|
|
168
|
-
* 无法互相 import(`@otto/plugin` 是 `@otto/coding` 的依赖,反向 import 会成环)。收敛到零依赖的
|
|
169
|
-
* `@otto/env`(两者共同的底层依赖)消除维护漂移风险(终局审核 finding,2026-07-09)。
|
|
170
|
-
*
|
|
171
|
-
* 终止条件用 `dirname(dir) === dir`(到达文件系统根)而非固定层数上限——后者在深层嵌套路径下
|
|
172
|
-
* 会误截断(旧实现的 `i < 20` 上限已移除,审核 finding:该上限是冗余约束)。
|
|
173
|
-
*/
|
|
174
|
-
//#endregion
|
|
175
161
|
//#region src/path.d.ts
|
|
176
162
|
declare function getProjectDir(): string;
|
|
177
163
|
declare function getHomeDir(): string;
|
|
@@ -206,7 +192,7 @@ declare function safeStringify(value: unknown, indent?: number): string;
|
|
|
206
192
|
/**
|
|
207
193
|
* glob-match.ts —— 轻量 glob 匹配(RFC-187 D6)。
|
|
208
194
|
*
|
|
209
|
-
* 用于文件名/相对路径匹配场景(非路径 specifier 语义,与 `@otto/setting`
|
|
195
|
+
* 用于文件名/相对路径匹配场景(非路径 specifier 语义,与 `@x-otto/setting`
|
|
210
196
|
* `globToRegexSource` 的 `~` 展开/绝对路径锚定正交,各自独立实现——本函数不做
|
|
211
197
|
* `~` 展开,返回 boolean 而非 regex 字符串,且默认大小写不敏感)。
|
|
212
198
|
*
|
|
@@ -217,7 +203,7 @@ declare function safeStringify(value: unknown, indent?: number): string;
|
|
|
217
203
|
* 已知边界(RFC-187 R8):`**` 是简单字符串替换为 `.*`,与相邻字面斜杠之间
|
|
218
204
|
* 不做"零或多层目录"的特殊语义——形如 "**" + 斜杠 + "*.proto" 的模式不匹配无前导
|
|
219
205
|
* 目录的 "c.proto",形如 "a" + 斜杠 + "**" + 斜杠 + "b" 的模式不匹配 "a/b"("**"
|
|
220
|
-
* 不能吸收相邻的字面斜杠)。这是与 `@otto/setting` `globToRegexSource` 同款的简单
|
|
206
|
+
* 不能吸收相邻的字面斜杠)。这是与 `@x-otto/setting` `globToRegexSource` 同款的简单
|
|
221
207
|
* 转换限制,非 bug。插件作者/matcher 声明方需要"零或多层"语义时应显式声明不带
|
|
222
208
|
* 前导/尾随双星号斜杠的等价模式(如同时声明 `*.proto` 覆盖顶层),而非依赖 `**`
|
|
223
209
|
* 自动吸收空目录段。
|
|
@@ -246,7 +232,7 @@ declare function createDispatcher(proxyUrl?: string): ProxyAgent | undefined;
|
|
|
246
232
|
* dispatcher,使进程内**所有** `fetch()` 自动经代理——包括各包直接裸调 `fetch` 的路径
|
|
247
233
|
* (OAuth token 交换、远端持久化、install/upgrade 检查、service 登录等)。
|
|
248
234
|
*
|
|
249
|
-
* 背景(RFC-288 §背景·第零类):此前代理只对 `@otto/shared` 的 `request()`/`stream()`
|
|
235
|
+
* 背景(RFC-288 §背景·第零类):此前代理只对 `@x-otto/shared` 的 `request()`/`stream()`
|
|
250
236
|
* 生效,全仓仅 1 个 import;Anthropic 走官方 SDK 未传 dispatcher,Node 22 内置 fetch 又
|
|
251
237
|
* 不读 `HTTP_PROXY` 环境变量——导致「面板显示已启用但 Claude 请求直连」的静默失败。
|
|
252
238
|
* 选择全局兜底而非逐个调用点接线,正是因为后者的漏接线成本已被这次事故证明。
|
|
@@ -466,12 +452,12 @@ declare const API_IMAGE_DIMENSION_LIMIT_PX = 8000;
|
|
|
466
452
|
* 底层约束是 provider(Anthropic)对单图输入的字节上限。此前四处各自硬编码 5MB 并靠
|
|
467
453
|
* 注释「与 XX 对齐 / 变更时同步更新 XX」手动维护,是漂移反模式。收敛到本处(provider
|
|
468
454
|
* 图片约束常量的既有归属地,与上面的维度上限同域)。四处消费方:
|
|
469
|
-
* - `@otto/tools` fs/read.ts(读取本地图片文件的字节上限)
|
|
470
|
-
* - `@otto/mcp` mcp-tool-adapter.ts(MCP 工具产出图片的字节上限)
|
|
471
|
-
* - `@otto/tui` input/clipboard-image.ts(剪贴板图片的字节上限)
|
|
472
|
-
* - `@otto/agent` tool-result-clamp.ts(RFC-151 D2:image 块内联上限,超限走 spill)
|
|
455
|
+
* - `@x-otto/tools` fs/read.ts(读取本地图片文件的字节上限)
|
|
456
|
+
* - `@x-otto/mcp` mcp-tool-adapter.ts(MCP 工具产出图片的字节上限)
|
|
457
|
+
* - `@x-otto/tui` input/clipboard-image.ts(剪贴板图片的字节上限)
|
|
458
|
+
* - `@x-otto/agent` tool-result-clamp.ts(RFC-151 D2:image 块内联上限,超限走 spill)
|
|
473
459
|
*
|
|
474
|
-
* **不做 env 覆盖**(刻意):`@otto/agent` 是确定性纯引擎(RFC-192,零 env 读取以保证
|
|
460
|
+
* **不做 env 覆盖**(刻意):`@x-otto/agent` 是确定性纯引擎(RFC-192,零 env 读取以保证
|
|
475
461
|
* 重放一致性),若本常量经 env 求值,agent 消费的值会随环境漂移、破坏 record/replay 不
|
|
476
462
|
* 变式。故保持字面量;未来若需可调,应经注入传入 agent,而非改本常量为 env 读取。
|
|
477
463
|
*
|
|
@@ -602,7 +588,7 @@ declare function rankLabeledItems<T extends {
|
|
|
602
588
|
declare const DEFAULT_FILE_LOCK_TIMEOUT_MS = 15000;
|
|
603
589
|
/** 锁文件路径:`<dir>/.file-lock-<key>.lock`。调用方通过 dir/key 组合天然隔离不同锁域。
|
|
604
590
|
*
|
|
605
|
-
* RFC-303 D7:命名格式的调用方(`@otto/ai` 的 oauth-refresh-lock.ts)有滚动升级兼容
|
|
591
|
+
* RFC-303 D7:命名格式的调用方(`@x-otto/ai` 的 oauth-refresh-lock.ts)有滚动升级兼容
|
|
606
592
|
* 硬约束——历史锁文件名是 `.auth-refresh-<provider>.lock`,若本函数改变格式会导致
|
|
607
593
|
* 新旧进程各锁各的文件、互斥失效。故格式做成可参数化:`prefix` 缺省 `file-lock`
|
|
608
594
|
* (新调用方用默认值),历史调用方显式传入 `auth-refresh` 保持字节级不变。
|
|
@@ -613,7 +599,7 @@ interface FileLockOptions {
|
|
|
613
599
|
timeoutMs?: number;
|
|
614
600
|
/**
|
|
615
601
|
* 锁文件名前缀(`.{prefix}-{key}.lock`)。缺省 `'file-lock'`。
|
|
616
|
-
* 历史调用方(如 `@otto/ai` 的 oauth-refresh-lock.ts)需显式传入其历史前缀
|
|
602
|
+
* 历史调用方(如 `@x-otto/ai` 的 oauth-refresh-lock.ts)需显式传入其历史前缀
|
|
617
603
|
* (`'auth-refresh'`)以保持锁文件名字节级不变——改变格式会破坏滚动升级期
|
|
618
604
|
* 新旧进程的互斥(各锁各的文件,等于没锁)。
|
|
619
605
|
*/
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{n as e,t}from"./event-bus-CABu09lC.js";import{createRequire as n}from"node:module";import r from"pino";import{LOG_FILE as i,LOG_LEVEL as a,OTTO_HOME as o,OTTO_PROJECT_DIR as s,normalizePath as c}from"@otto/env";import{PassThrough as l}from"node:stream";import{chmod as u,mkdir as d,open as f,readFile as p,readdir as m,stat as h,unlink as g,utimes as ee}from"node:fs/promises";import{lookup as te}from"mime-types";import{join as _,resolve as ne}from"node:path";import{tmpdir as v}from"node:os";import{createHash as re,randomBytes as ie,randomUUID as y}from"node:crypto";import{parse as ae,printParseErrorCode as oe}from"jsonc-parser";import se from"safe-stable-stringify";import{createParser as ce}from"eventsource-parser";import{EnvHttpProxyAgent as le,ProxyAgent as ue,getGlobalDispatcher as de,setGlobalDispatcher as fe}from"undici";import{createServer as pe}from"node:http";import{spawn as me}from"node:child_process";import{chmodSync as he,closeSync as ge,mkdirSync as _e,openSync as ve,readFileSync as ye,statSync as be,unlinkSync as xe,writeSync as Se}from"node:fs";var b=class extends Error{code;cause;status;headers;errorType;pluginSource;constructor(e,t){super(e,{cause:t.cause}),this.name=new.target.name,this.code=t.code,this.cause=t.cause,this.status=t.status,this.headers=t.headers,this.errorType=t.errorType,this.pluginSource=t.pluginSource}},x=class extends b{},Ce=class extends b{},S=class extends b{},we=class extends b{},Te=class extends b{};const{setPrototypeOf:Ee=function(e,t){return e.__proto__=t,e}}=Object;var C=class e extends Error{framesToPop=1;name=`Invariant Violation`;constructor(t=`Invariant Violation`){super(typeof t==`number`?`Invariant Violation: ${t}`:t),Ee(this,e.prototype)}};function w(e,t){if(typeof e==`function`)w(e(),t);else if(!e)throw new C(t)}const De=new Set([`trace`,`debug`,`info`,`warn`,`error`,`fatal`]);function T(e){return De.has(e)?e:`info`}const Oe=(()=>{try{return n(import.meta.url)}catch{return}})();function ke(){if(!Oe)return!1;try{return Oe.resolve(`pino-pretty`),!0}catch{return!1}}function Ae(e){return e===`stdout`?1:e===`stderr`?2:e}function je(){return process.env.OTTO_LOG_STDERR===`0`}function Me(){return process.env.OTTO_LOG_FILE||`${process.env.HOME||process.env.USERPROFILE||`.`}/.otto/logs/otto.log`}function Ne(e,t){let n=ke(),r=je(),i={target:n?`pino-pretty`:`pino/file`,options:n?{colorize:!0,destination:2}:{destination:2},level:t};if(!e||e===`stdout`||e===`stderr`)return r?[{target:`pino/file`,options:{destination:Me(),mkdir:!0},level:t}]:[i];let a={target:`pino/file`,options:{destination:Ae(e),mkdir:!0},level:t};return r?[a]:[a,i]}const E=new l,D=new t;E.on(`data`,e=>{try{D.publish({log:[JSON.parse(e.toString())]})}catch(t){console.warn(`Failed to parse log chunk for listener:`,e.toString(),t)}});function Pe(e){return D.subscribe(`log`,e)}let O=null,k=T(a);const Fe=new Set;function Ie(e){if(De.has(e)){k=e,O&&(O.level=e);for(let t of Fe)t.level=e}}function Le(){return A!==null}let A=null;function Re(e,t){return{write(n){A??=r.transport({targets:Ne(e,t)}),A.write(n)}}}function ze(e,t){return O??=r({level:e},r.multistream([{level:e,stream:E},{level:e,stream:Re(t,e)}])),k=T(O.level),O}function Be(e,t){ze(t?.level??T(a),t?.destination??i),w(O,`Root logger is not initialized`);let n=O.child({name:e},{level:t?.level??k});return Fe.add(n),n}const j=10*1024*1024;async function Ve(e){return te(e)||`application/octet-stream`}async function He(e){await d(e,{recursive:!0})}async function Ue(e){try{return await h(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function We(e){return(await h(e)).isDirectory()}async function Ge(e){return(await h(e)).isFile()}async function Ke(e,t=j){let n=await h(e);if(n.size<=t)return{content:await p(e,`utf-8`),truncated:!1,totalBytes:n.size};let r=await f(e,`r`);try{let e=Buffer.alloc(t),{bytesRead:i}=await r.read(e,0,t,0);return{content:e.subarray(0,i).toString(`utf-8`),truncated:!0,totalBytes:n.size}}finally{await r.close()}}function qe(e){let{content:t,...n}=e;return n}function Je(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/(1024*1024)).toFixed(1)}MB`}function M(e){let t=e.outputBytes??Buffer.byteLength(e.content,`utf-8`),n=e.outputLines??e.content.split(`
|
|
1
|
+
import{n as e,t}from"./event-bus-CABu09lC.js";import{createRequire as n}from"node:module";import r from"pino";import{LOG_FILE as i,LOG_LEVEL as a,OTTO_HOME as o,OTTO_PROJECT_DIR as s,normalizePath as c}from"@x-otto/env";import{PassThrough as l}from"node:stream";import{chmod as u,mkdir as d,open as f,readFile as p,readdir as m,stat as h,unlink as g,utimes as ee}from"node:fs/promises";import{lookup as te}from"mime-types";import{join as _,resolve as ne}from"node:path";import{tmpdir as v}from"node:os";import{createHash as re,randomBytes as ie,randomUUID as y}from"node:crypto";import{parse as ae,printParseErrorCode as oe}from"jsonc-parser";import se from"safe-stable-stringify";import{createParser as ce}from"eventsource-parser";import{EnvHttpProxyAgent as le,ProxyAgent as ue,getGlobalDispatcher as de,setGlobalDispatcher as fe}from"undici";import{createServer as pe}from"node:http";import{spawn as me}from"node:child_process";import{chmodSync as he,closeSync as ge,mkdirSync as _e,openSync as ve,readFileSync as ye,statSync as be,unlinkSync as xe,writeSync as Se}from"node:fs";var b=class extends Error{code;cause;status;headers;errorType;pluginSource;constructor(e,t){super(e,{cause:t.cause}),this.name=new.target.name,this.code=t.code,this.cause=t.cause,this.status=t.status,this.headers=t.headers,this.errorType=t.errorType,this.pluginSource=t.pluginSource}},x=class extends b{},Ce=class extends b{},S=class extends b{},we=class extends b{},Te=class extends b{};const{setPrototypeOf:Ee=function(e,t){return e.__proto__=t,e}}=Object;var C=class e extends Error{framesToPop=1;name=`Invariant Violation`;constructor(t=`Invariant Violation`){super(typeof t==`number`?`Invariant Violation: ${t}`:t),Ee(this,e.prototype)}};function w(e,t){if(typeof e==`function`)w(e(),t);else if(!e)throw new C(t)}const De=new Set([`trace`,`debug`,`info`,`warn`,`error`,`fatal`]);function T(e){return De.has(e)?e:`info`}const Oe=(()=>{try{return n(import.meta.url)}catch{return}})();function ke(){if(!Oe)return!1;try{return Oe.resolve(`pino-pretty`),!0}catch{return!1}}function Ae(e){return e===`stdout`?1:e===`stderr`?2:e}function je(){return process.env.OTTO_LOG_STDERR===`0`}function Me(){return process.env.OTTO_LOG_FILE||`${process.env.HOME||process.env.USERPROFILE||`.`}/.otto/logs/otto.log`}function Ne(e,t){let n=ke(),r=je(),i={target:n?`pino-pretty`:`pino/file`,options:n?{colorize:!0,destination:2}:{destination:2},level:t};if(!e||e===`stdout`||e===`stderr`)return r?[{target:`pino/file`,options:{destination:Me(),mkdir:!0},level:t}]:[i];let a={target:`pino/file`,options:{destination:Ae(e),mkdir:!0},level:t};return r?[a]:[a,i]}const E=new l,D=new t;E.on(`data`,e=>{try{D.publish({log:[JSON.parse(e.toString())]})}catch(t){console.warn(`Failed to parse log chunk for listener:`,e.toString(),t)}});function Pe(e){return D.subscribe(`log`,e)}let O=null,k=T(a);const Fe=new Set;function Ie(e){if(De.has(e)){k=e,O&&(O.level=e);for(let t of Fe)t.level=e}}function Le(){return A!==null}let A=null;function Re(e,t){return{write(n){A??=r.transport({targets:Ne(e,t)}),A.write(n)}}}function ze(e,t){return O??=r({level:e},r.multistream([{level:e,stream:E},{level:e,stream:Re(t,e)}])),k=T(O.level),O}function Be(e,t){ze(t?.level??T(a),t?.destination??i),w(O,`Root logger is not initialized`);let n=O.child({name:e},{level:t?.level??k});return Fe.add(n),n}const j=10*1024*1024;async function Ve(e){return te(e)||`application/octet-stream`}async function He(e){await d(e,{recursive:!0})}async function Ue(e){try{return await h(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function We(e){return(await h(e)).isDirectory()}async function Ge(e){return(await h(e)).isFile()}async function Ke(e,t=j){let n=await h(e);if(n.size<=t)return{content:await p(e,`utf-8`),truncated:!1,totalBytes:n.size};let r=await f(e,`r`);try{let e=Buffer.alloc(t),{bytesRead:i}=await r.read(e,0,t,0);return{content:e.subarray(0,i).toString(`utf-8`),truncated:!0,totalBytes:n.size}}finally{await r.close()}}function qe(e){let{content:t,...n}=e;return n}function Je(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/(1024*1024)).toFixed(1)}MB`}function M(e){let t=e.outputBytes??Buffer.byteLength(e.content,`utf-8`),n=e.outputLines??e.content.split(`
|
|
2
2
|
`).length;return{content:e.content,truncated:e.truncated,truncatedBy:e.truncatedBy,totalLines:e.totalLines,totalBytes:e.totalBytes,outputLines:n,outputBytes:t,lastLinePartial:e.lastLinePartial,firstLineExceedsLimit:e.firstLineExceedsLimit,options:e.options}}function Ye(e,t){let{maxLines:n,maxBytes:r}=t,i=Buffer.byteLength(e,`utf-8`),a=e.split(`
|
|
3
3
|
`),o=a.length;if(a.length<=n&&i<=r)return M({content:e,truncated:!1,truncatedBy:`lines`,totalLines:o,totalBytes:i,lastLinePartial:!1,firstLineExceedsLimit:!1,options:{maxLines:n,maxBytes:r},outputLines:o,outputBytes:i});if(n===0)return M({content:``,truncated:!0,truncatedBy:`lines`,totalLines:o,totalBytes:i,lastLinePartial:!1,firstLineExceedsLimit:!1,options:{maxLines:n,maxBytes:r},outputLines:0,outputBytes:0});if(Buffer.byteLength(a[0],`utf-8`)>r)return M({content:``,truncated:!0,truncatedBy:`bytes`,totalLines:o,totalBytes:i,lastLinePartial:!1,firstLineExceedsLimit:!0,options:{maxLines:n,maxBytes:r},outputLines:0,outputBytes:0});let s=[],c=0,l=`lines`;for(let e=0;e<a.length&&e<n;e++){let t=a[e],n=Buffer.byteLength(t,`utf-8`)+(s.length>0?1:0);if(c+n>r){l=`bytes`;break}s.push(t),c+=n}return s.length>=n&&c<=r&&(l=`lines`),M({content:s.join(`
|
|
4
4
|
`),truncated:!0,truncatedBy:l,totalLines:o,totalBytes:i,lastLinePartial:!1,firstLineExceedsLimit:!1,options:{maxLines:n,maxBytes:r},outputLines:s.length,outputBytes:c})}function Xe(e,t){let{maxLines:n,maxBytes:r}=t,i=Buffer.byteLength(e,`utf-8`),a=e.split(`
|
|
@@ -87,4 +87,4 @@ import{n as e,t}from"./event-bus-CABu09lC.js";import{createRequire as n}from"nod
|
|
|
87
87
|
</main>
|
|
88
88
|
</body>
|
|
89
89
|
</html>`}const Mt=jt(`success`,`Login complete`,`You can close this window and return to the terminal.`,`Otto Auth`);function W(e){return jt(`error`,`Login failed`,e,`Otto Auth`)}function G(e,t,n){let r=Buffer.from(n,`utf-8`);e.writeHead(t,{"Content-Type":`text/html; charset=utf-8`,"Content-Length":String(r.length),Connection:`close`}),e.end(r)}function Nt(e,t,n){return new Promise((r,i)=>{if(n.length===0){i(new S(`No loopback port specified.`,{code:`OAUTH_LOOPBACK_PORT_UNAVAILABLE`}));return}let a=0,o=()=>{e.removeListener(`error`,l),e.removeListener(`listening`,c)},s=()=>{let r=n[a++];e.listen(r,t)},c=()=>{o();let t=e.address();r(typeof t==`object`&&t?t.port:n[a-1])},l=e=>{if(e.code===`EADDRINUSE`||e.code===`EACCES`){if(a<n.length){s();return}o(),i(new S(`No available loopback port among: ${n.join(`, `)}`,{code:`OAUTH_LOOPBACK_PORT_UNAVAILABLE`}));return}o(),i(e)};e.on(`error`,l),e.on(`listening`,c),s()})}function Pt(e,t){e.value||(e.value=!0,t())}async function Ft(e={}){let{ports:t=Dt,callbackPath:n=`/auth/callback`,expectedState:r,host:i=`127.0.0.1`,signal:a}=e;if(a?.aborted)throw new S(`Login cancelled`,{code:`OAUTH_CANCELLED`});let o,s,c={value:!1},l=new Promise((e,t)=>{o=t=>Pt(c,()=>e(t)),s=e=>Pt(c,()=>t(e))});l.catch(()=>{});let u=0,d=()=>`http://${i}:${u}`,f=pe((e,t)=>{let i;try{i=new URL(e.url??`/`,d())}catch{G(t,400,W(`Invalid request URL`)),s(new S(`Invalid callback URL`,{code:`OAUTH_INVALID_REQUEST`}));return}if(i.pathname!==n){G(t,404,W(`Not found`));return}let a=i.searchParams.get(`error`);if(a){let e=i.searchParams.get(`error_description`)??``;G(t,400,W(e||a)),s(new S(`Authorization failed: ${a}${e?`: ${e}`:``}`,{code:`OAUTH_AUTHORIZE_FAILED`}));return}let c=i.searchParams.get(`code`);if(!c){G(t,400,W(`Missing authorization code.`)),s(new S(`Callback missing authorization code.`,{code:`OAUTH_AUTHORIZE_FAILED`}));return}let l=i.searchParams.get(`state`)??void 0;if(r!==void 0&&l!==r){G(t,400,W(`State mismatch.`)),s(new S(`OAuth state mismatch (possible CSRF).`,{code:`OAUTH_STATE_MISMATCH`}));return}G(t,200,Mt),o({code:c,state:l})});u=await Nt(f,i,t);let p=!1,m=()=>new Promise(e=>{if(p){e();return}p=!0,s(new S(`Login cancelled (server closed)`,{code:`OAUTH_CANCELLED`})),f.close(()=>e()),f.closeAllConnections?.()});return a&&a.addEventListener(`abort`,()=>{s(new S(`Login cancelled`,{code:`OAUTH_CANCELLED`})),m()},{once:!0}),{port:u,redirectUri:`${d()}${n}`,waitForCallback:()=>l,close:m}}function It(e){try{new URL(e)}catch{return!1}try{let t=process.platform,n=t===`darwin`?[`open`,[e]]:t===`win32`?[`cmd`,[`/c`,`start`,``,e]]:[`xdg-open`,[e]];return me(n[0],[...n[1]],{detached:!0,stdio:`ignore`}).unref(),!0}catch{return!1}}const Lt=/^---\s*\n([\s\S]*?)\n---\s*\n?([\s\S]*)$/;function Rt(e){let t=Lt.exec(e);return t?{fields:zt(t[1]??``),body:(t[2]??``).trim()}:null}function zt(e){let t=new Map;for(let n of e.split(`
|
|
90
|
-
`)){let e=n.indexOf(`:`);if(e<=0)continue;let r=n.slice(0,e).trim().toLowerCase().replaceAll(`_`,``),i=n.slice(e+1).trim().replace(/^["']|["']$/g,``);r&&i&&t.set(r,i)}return t}function Bt(e){if(!e)return;let t=(e.startsWith(`[`)&&e.endsWith(`]`)?e.slice(1,-1):e).split(`,`).map(e=>e.trim().replace(/^["']|["']$/g,``)).filter(e=>e!==``);return t.length>0?t:void 0}const Vt=8e3,Ht=5*1024*1024,Ut=Buffer.from([137,80,78,71,13,10,26,10]),Wt=Buffer.from(`GIF8`,`ascii`);function Gt(e,t){if(!(!e||e.length===0)&&!(e.length>7340032))try{return Kt(Buffer.from(e.slice(0,128),`base64`),e,t)}catch{return}}function Kt(e,t,n){let r=n.toLowerCase();if(r.includes(`png`))return qt(e);if(r.includes(`jpeg`)||r.includes(`jpg`))return Jt(Buffer.from(t,`base64`));if(r.includes(`gif`))return Yt(e);if(r.includes(`webp`))return Xt(e);if(e.length>=8&&e.subarray(0,8).equals(Ut))return qt(e);if(e.length>=2&&e.readUInt16BE(0)===65496)return Jt(Buffer.from(t,`base64`));if(e.length>=4&&e.subarray(0,4).equals(Wt))return Yt(e);if(e.length>=12&&e.readUInt32BE(0)===1380533830&&e.readUInt32BE(8)===1464156752)return Xt(e)}function qt(e){if(!(e.length<24)&&e.subarray(0,8).equals(Ut))try{return e.toString(`ascii`,12,16)===`IHDR`?{width:e.readUInt32BE(16),height:e.readUInt32BE(20)}:void 0}catch{return}}function Jt(e){if(!(e.length<2))try{let t=2,n=0;for(;t<e.length-1;){if(n++,n>1e5)return;let r=e.readUInt16BE(t);if(r===65497||(r&65280)!=65280)return;let i=r&255;if(i>=192&&i<=195||i>=197&&i<=199||i>=201&&i<=203||i>=205&&i<=207){if(t+9>e.length||e.readUInt16BE(t+2)<8)return;let n=e.readUInt16BE(t+5);return{width:e.readUInt16BE(t+7),height:n}}if(i===216||i===217){t+=2;continue}if(t+4>e.length)return;let a=e.readUInt16BE(t+2);if(a<2)return;t+=2+a}return}catch{return}}function Yt(e){if(!(e.length<10)&&e.subarray(0,4).equals(Wt))try{return{width:e.readUInt16LE(6),height:e.readUInt16LE(8)}}catch{return}}function Xt(e){if(!(e.length<16)&&!(e.readUInt32BE(0)!==1380533830||e.readUInt32BE(8)!==1464156752))try{let t=e.toString(`ascii`,12,16);return t===`VP8X`?Zt(e):t===`VP8 `?Qt(e):t===`VP8L`?$t(e):void 0}catch{return}}function Zt(e){if(!(e.length<30))return{width:(e[24]|e[25]<<8|e[26]<<16)+1,height:(e[27]|e[28]<<8|e[29]<<16)+1}}function Qt(e){if(e.length<30)return;let t=e.readUInt16LE(26)&16383,n=e.readUInt16LE(28)&16383;if(!(t===0||n===0))return{width:t,height:n}}function $t(e){if(e.length<25||e[20]!==47)return;let t=e.readUInt32LE(21);return{width:(t&16383)+1,height:(t>>14&16383)+1}}const K=process.env.OTTO_STARTUP_TRACE===`1`,en=K?performance.now():0;function tn(e){if(!K)return;let t=performance.now()-en;process.stderr.write(`[startup] ${e}: ${t.toFixed(1)}ms\n`)}async function nn(e,t){if(!K)return t();let n=performance.now();try{return await t()}finally{let t=performance.now()-n;process.stderr.write(`[startup] ${e}: ${t.toFixed(1)}ms\n`)}}function rn(e,t){if(!K)return t();let n=performance.now();try{return t()}finally{let t=performance.now()-n;process.stderr.write(`[startup] ${e}: ${t.toFixed(1)}ms\n`)}}function an(){return K}const on=/[/\-_\s.]/;function sn(e){return e!==void 0&&on.test(e)}function q(e,t){if(e.length===0)return{score:0,positions:[]};if(t.length===0)return null;let n=e.toLowerCase(),r=t.toLowerCase(),i=0,a=0,o=[],s=-2;for(let e=0;e<r.length&&a<n.length;e++)r[e]===n[a]&&(s===e-1?i+=24:(i+=16,s>=0&&(i-=(e-s-1)*3)),e===0?i+=12:sn(r[e-1])&&(i+=8),o.push(e),s=e,a++);return a<n.length?null:(i-=Math.max(0,r.length-n.length)*.5,{score:i,positions:o})}function cn(e,t){return q(e,t)?.score??-1}function ln(e){if(e.length===0)return[];let t=[],n=e[0],r=n+1;for(let i=1;i<e.length;i++){let a=e[i];a===r?r++:(t.push({start:n,end:r}),n=a,r=a+1)}return t.push({start:n,end:r}),t}function un(e,t,n){let r=q(e,t);for(let t of n??[]){let n=q(e,t);n&&(!r||n.score>r.score)&&(r=n)}return r}function J(e,t,n={}){let r=n.maxResults??50,i=n.matchEmpty??!0,a=t.trim();if(a===``)return i?e.slice(0,r).map(e=>({item:e,score:0,highlightRanges:[]})):[];let o=[];for(let t of e){let e=un(a,t.text,t.aliases);if(!e)continue;let n=q(a,t.text);o.push({item:t,score:e.score,highlightRanges:ln(n?.positions??[])})}return o.sort((e,t)=>t.score-e.score||(e.item.sortKey??e.item.text).localeCompare(t.item.sortKey??t.item.text)),o.slice(0,r)}function dn(e,t,n){return J(e.map(e=>({text:e.name,aliases:e.description?[e.description]:void 0,payload:e,sortKey:e.sortKey})),t,n).map(e=>e.item.payload)}function fn(e,t,n){return J(e.map(e=>({text:e.searchText??e.label,aliases:[e.group,e.detail,e.value].filter(e=>!!e),payload:e})),t,{maxResults:n?.maxResults??e.length,matchEmpty:n?.matchEmpty}).map(e=>e.item.payload)}const Y=Be(`@otto/shared:file-lock`),pn=15e3;function mn(e){return Math.floor(e/3)}const X=new Map,Z=new Map;function Q(e,t,n=`file-lock`){return _(e,`.${n}-${t}.lock`)}function hn(e,t){gn(e);let n=setInterval(()=>{let t=new Date;ee(e,t,t).catch(()=>{})},mn(t));n.unref?.(),X.set(e,n)}function gn(e){let t=X.get(e);t&&(clearInterval(t),X.delete(e))}async function _n(e,t,n={}){let r=n.timeoutMs??15e3,i=Q(e,t,n.prefix),a=async(n=!1)=>{try{let e=await f(i,`wx`),t=y();await e.writeFile(t),await e.close(),Z.set(i,t);try{await u(i,384)}catch{}return hn(i,r),!0}catch(r){if(r.code===`EEXIST`)return!1;if(r.code===`ENOENT`&&!n){try{await d(e,{recursive:!0})}catch(e){return Y.warn(`Failed to create lock directory for ${t}: ${e.message}`),!1}return await a(!0)}return Y.warn(`Failed to acquire file lock for ${t}: ${r.message}`),!1}};if(await a())return!0;try{let e=await h(i);if(Date.now()-e.mtimeMs>r)return await g(i).catch(()=>{}),await a()}catch{return await a()}return!1}async function vn(e,t,n={}){let r=Q(e,t,n.prefix);gn(r);let i=Z.get(r);if(Z.delete(r),i!==void 0)try{if(await p(r,`utf-8`)!==i){Y.warn(`File lock ownership drifted for ${t} — another process stole this lock (likely stale-lock takeover during a heartbeat gap). Skipping unlink to avoid deleting the new owner's lock.`);return}}catch{}await g(r).catch(()=>{})}async function yn(e,t,n={}){let r=n.timeoutMs??15e3,i=Q(e,t,n.prefix),a=Date.now()+r;for(;Date.now()<a;){try{await h(i)}catch{return!0}await new Promise(e=>setTimeout(e,100))}return!1}const $=new Map;function bn(e,t,n={}){let r=n.timeoutMs??15e3,i=Q(e,t,n.prefix),a=(n=!1)=>{let r;try{r=ve(i,`wx`)}catch(r){let i=r.code;if(i===`EEXIST`)return!1;if(i===`ENOENT`&&!n){try{_e(e,{recursive:!0})}catch(e){return Y.warn(`Failed to create lock directory for ${t}: ${e.message}`),!1}return a(!0)}return Y.warn(`Failed to acquire file lock for ${t}: ${r.message}`),!1}let o=y();try{Se(r,o)}finally{ge(r)}$.set(i,o);try{he(i,384)}catch{}return!0};if(a())return!0;try{let e=be(i);if(Date.now()-e.mtimeMs>r){try{xe(i)}catch{}return a()}}catch{return a()}return!1}function xn(e,t,n={}){let r=Q(e,t,n.prefix),i=$.get(r);if($.delete(r),i!==void 0)try{if(ye(r,`utf-8`)!==i){Y.warn(`File lock ownership drifted for ${t} — another process stole this lock. Skipping unlink to avoid deleting the new owner's lock.`);return}}catch{}try{xe(r)}catch{}}function Sn(e,t,n={}){let r=n.timeoutMs??15e3,i=Q(e,t,n.prefix),a=Date.now()+r,o=new Int32Array(new SharedArrayBuffer(4));for(;Date.now()<a;){try{be(i)}catch{return!0}Atomics.wait(o,0,0,100)}return!1}export{Vt as API_IMAGE_DIMENSION_LIMIT_PX,we as AgentError,z as CLAUDE_TO_OTTO_TOOL,b as CodedError,pn as DEFAULT_FILE_LOCK_TIMEOUT_MS,t as EventBus,C as InvariantError,j as LARGE_FILE_BYTE_THRESHOLD,Te as McpError,x as NetworkError,S as OAuthError,Ht as PROVIDER_IMAGE_INLINE_MAX_BYTES,Ce as ProviderError,e as TypedEventEmitter,_n as acquireFileLock,bn as acquireFileLockSync,Pe as attachLogListener,bt as buildAllowedEnv,yt as checkShellCommand,L as createDispatcher,Be as createLogger,Tt as createPkcePair,rt as createProjectOverflowLogPath,nt as createTempLoggerPath,Ue as exists,Je as formatBytes,H as generateChallenge,Et as generateState,V as generateVerifier,dt as getDefaultProxy,$e as getHomeDir,F as getProjectDir,tt as getThirdPartyToolBinaryDir,et as getThirdPartyToolDir,_t as headerGet,ft as installGlobalProxyDispatcher,w as invariant,We as isDirectory,Ge as isFile,an as isStartupTraceEnabled,Le as isTransportInitialized,Q as lockPath,wt as mapClaudeAgentToolNames,xt as mapClaudeToolName,tn as markStartupPhase,q as matchSubsequence,lt as matchesGlobPattern,Ve as mime,He as mkdirp,c as normalizePath,It as openBrowser,Ct as ottoToClaudeToolName,zt as parseFrontmatterFields,Bt as parseFrontmatterList,st as parseJsonc,ln as positionsToHighlightRanges,Gt as probeImageDimensions,pt as probeProxy,J as rankCandidates,fn as rankLabeledItems,dn as rankNamedItems,Ke as readFileCapped,vn as releaseFileLock,xn as releaseFileLockSync,ht as request,ct as safeStringify,cn as scoreSubsequence,ut as setDefaultProxy,Ie as setLogLevel,Rt as splitFrontmatter,Ft as startLoopbackServer,gt as stream,at as sweepStaleProjectOverflowLogs,it as sweepStaleTempLogs,qe as toTruncationMeta,nn as traceStartupPhase,rn as traceStartupPhaseSync,Ye as truncateHead,Qe as truncateLine,Xe as truncateTail,yn as waitForFileLockRelease,Sn as waitForFileLockReleaseSync};
|
|
90
|
+
`)){let e=n.indexOf(`:`);if(e<=0)continue;let r=n.slice(0,e).trim().toLowerCase().replaceAll(`_`,``),i=n.slice(e+1).trim().replace(/^["']|["']$/g,``);r&&i&&t.set(r,i)}return t}function Bt(e){if(!e)return;let t=(e.startsWith(`[`)&&e.endsWith(`]`)?e.slice(1,-1):e).split(`,`).map(e=>e.trim().replace(/^["']|["']$/g,``)).filter(e=>e!==``);return t.length>0?t:void 0}const Vt=8e3,Ht=5*1024*1024,Ut=Buffer.from([137,80,78,71,13,10,26,10]),Wt=Buffer.from(`GIF8`,`ascii`);function Gt(e,t){if(!(!e||e.length===0)&&!(e.length>7340032))try{return Kt(Buffer.from(e.slice(0,128),`base64`),e,t)}catch{return}}function Kt(e,t,n){let r=n.toLowerCase();if(r.includes(`png`))return qt(e);if(r.includes(`jpeg`)||r.includes(`jpg`))return Jt(Buffer.from(t,`base64`));if(r.includes(`gif`))return Yt(e);if(r.includes(`webp`))return Xt(e);if(e.length>=8&&e.subarray(0,8).equals(Ut))return qt(e);if(e.length>=2&&e.readUInt16BE(0)===65496)return Jt(Buffer.from(t,`base64`));if(e.length>=4&&e.subarray(0,4).equals(Wt))return Yt(e);if(e.length>=12&&e.readUInt32BE(0)===1380533830&&e.readUInt32BE(8)===1464156752)return Xt(e)}function qt(e){if(!(e.length<24)&&e.subarray(0,8).equals(Ut))try{return e.toString(`ascii`,12,16)===`IHDR`?{width:e.readUInt32BE(16),height:e.readUInt32BE(20)}:void 0}catch{return}}function Jt(e){if(!(e.length<2))try{let t=2,n=0;for(;t<e.length-1;){if(n++,n>1e5)return;let r=e.readUInt16BE(t);if(r===65497||(r&65280)!=65280)return;let i=r&255;if(i>=192&&i<=195||i>=197&&i<=199||i>=201&&i<=203||i>=205&&i<=207){if(t+9>e.length||e.readUInt16BE(t+2)<8)return;let n=e.readUInt16BE(t+5);return{width:e.readUInt16BE(t+7),height:n}}if(i===216||i===217){t+=2;continue}if(t+4>e.length)return;let a=e.readUInt16BE(t+2);if(a<2)return;t+=2+a}return}catch{return}}function Yt(e){if(!(e.length<10)&&e.subarray(0,4).equals(Wt))try{return{width:e.readUInt16LE(6),height:e.readUInt16LE(8)}}catch{return}}function Xt(e){if(!(e.length<16)&&!(e.readUInt32BE(0)!==1380533830||e.readUInt32BE(8)!==1464156752))try{let t=e.toString(`ascii`,12,16);return t===`VP8X`?Zt(e):t===`VP8 `?Qt(e):t===`VP8L`?$t(e):void 0}catch{return}}function Zt(e){if(!(e.length<30))return{width:(e[24]|e[25]<<8|e[26]<<16)+1,height:(e[27]|e[28]<<8|e[29]<<16)+1}}function Qt(e){if(e.length<30)return;let t=e.readUInt16LE(26)&16383,n=e.readUInt16LE(28)&16383;if(!(t===0||n===0))return{width:t,height:n}}function $t(e){if(e.length<25||e[20]!==47)return;let t=e.readUInt32LE(21);return{width:(t&16383)+1,height:(t>>14&16383)+1}}const K=process.env.OTTO_STARTUP_TRACE===`1`,en=K?performance.now():0;function tn(e){if(!K)return;let t=performance.now()-en;process.stderr.write(`[startup] ${e}: ${t.toFixed(1)}ms\n`)}async function nn(e,t){if(!K)return t();let n=performance.now();try{return await t()}finally{let t=performance.now()-n;process.stderr.write(`[startup] ${e}: ${t.toFixed(1)}ms\n`)}}function rn(e,t){if(!K)return t();let n=performance.now();try{return t()}finally{let t=performance.now()-n;process.stderr.write(`[startup] ${e}: ${t.toFixed(1)}ms\n`)}}function an(){return K}const on=/[/\-_\s.]/;function sn(e){return e!==void 0&&on.test(e)}function q(e,t){if(e.length===0)return{score:0,positions:[]};if(t.length===0)return null;let n=e.toLowerCase(),r=t.toLowerCase(),i=0,a=0,o=[],s=-2;for(let e=0;e<r.length&&a<n.length;e++)r[e]===n[a]&&(s===e-1?i+=24:(i+=16,s>=0&&(i-=(e-s-1)*3)),e===0?i+=12:sn(r[e-1])&&(i+=8),o.push(e),s=e,a++);return a<n.length?null:(i-=Math.max(0,r.length-n.length)*.5,{score:i,positions:o})}function cn(e,t){return q(e,t)?.score??-1}function ln(e){if(e.length===0)return[];let t=[],n=e[0],r=n+1;for(let i=1;i<e.length;i++){let a=e[i];a===r?r++:(t.push({start:n,end:r}),n=a,r=a+1)}return t.push({start:n,end:r}),t}function un(e,t,n){let r=q(e,t);for(let t of n??[]){let n=q(e,t);n&&(!r||n.score>r.score)&&(r=n)}return r}function J(e,t,n={}){let r=n.maxResults??50,i=n.matchEmpty??!0,a=t.trim();if(a===``)return i?e.slice(0,r).map(e=>({item:e,score:0,highlightRanges:[]})):[];let o=[];for(let t of e){let e=un(a,t.text,t.aliases);if(!e)continue;let n=q(a,t.text);o.push({item:t,score:e.score,highlightRanges:ln(n?.positions??[])})}return o.sort((e,t)=>t.score-e.score||(e.item.sortKey??e.item.text).localeCompare(t.item.sortKey??t.item.text)),o.slice(0,r)}function dn(e,t,n){return J(e.map(e=>({text:e.name,aliases:e.description?[e.description]:void 0,payload:e,sortKey:e.sortKey})),t,n).map(e=>e.item.payload)}function fn(e,t,n){return J(e.map(e=>({text:e.searchText??e.label,aliases:[e.group,e.detail,e.value].filter(e=>!!e),payload:e})),t,{maxResults:n?.maxResults??e.length,matchEmpty:n?.matchEmpty}).map(e=>e.item.payload)}const Y=Be(`@x-otto/shared:file-lock`),pn=15e3;function mn(e){return Math.floor(e/3)}const X=new Map,Z=new Map;function Q(e,t,n=`file-lock`){return _(e,`.${n}-${t}.lock`)}function hn(e,t){gn(e);let n=setInterval(()=>{let t=new Date;ee(e,t,t).catch(()=>{})},mn(t));n.unref?.(),X.set(e,n)}function gn(e){let t=X.get(e);t&&(clearInterval(t),X.delete(e))}async function _n(e,t,n={}){let r=n.timeoutMs??15e3,i=Q(e,t,n.prefix),a=async(n=!1)=>{try{let e=await f(i,`wx`),t=y();await e.writeFile(t),await e.close(),Z.set(i,t);try{await u(i,384)}catch{}return hn(i,r),!0}catch(r){if(r.code===`EEXIST`)return!1;if(r.code===`ENOENT`&&!n){try{await d(e,{recursive:!0})}catch(e){return Y.warn(`Failed to create lock directory for ${t}: ${e.message}`),!1}return await a(!0)}return Y.warn(`Failed to acquire file lock for ${t}: ${r.message}`),!1}};if(await a())return!0;try{let e=await h(i);if(Date.now()-e.mtimeMs>r)return await g(i).catch(()=>{}),await a()}catch{return await a()}return!1}async function vn(e,t,n={}){let r=Q(e,t,n.prefix);gn(r);let i=Z.get(r);if(Z.delete(r),i!==void 0)try{if(await p(r,`utf-8`)!==i){Y.warn(`File lock ownership drifted for ${t} — another process stole this lock (likely stale-lock takeover during a heartbeat gap). Skipping unlink to avoid deleting the new owner's lock.`);return}}catch{}await g(r).catch(()=>{})}async function yn(e,t,n={}){let r=n.timeoutMs??15e3,i=Q(e,t,n.prefix),a=Date.now()+r;for(;Date.now()<a;){try{await h(i)}catch{return!0}await new Promise(e=>setTimeout(e,100))}return!1}const $=new Map;function bn(e,t,n={}){let r=n.timeoutMs??15e3,i=Q(e,t,n.prefix),a=(n=!1)=>{let r;try{r=ve(i,`wx`)}catch(r){let i=r.code;if(i===`EEXIST`)return!1;if(i===`ENOENT`&&!n){try{_e(e,{recursive:!0})}catch(e){return Y.warn(`Failed to create lock directory for ${t}: ${e.message}`),!1}return a(!0)}return Y.warn(`Failed to acquire file lock for ${t}: ${r.message}`),!1}let o=y();try{Se(r,o)}finally{ge(r)}$.set(i,o);try{he(i,384)}catch{}return!0};if(a())return!0;try{let e=be(i);if(Date.now()-e.mtimeMs>r){try{xe(i)}catch{}return a()}}catch{return a()}return!1}function xn(e,t,n={}){let r=Q(e,t,n.prefix),i=$.get(r);if($.delete(r),i!==void 0)try{if(ye(r,`utf-8`)!==i){Y.warn(`File lock ownership drifted for ${t} — another process stole this lock. Skipping unlink to avoid deleting the new owner's lock.`);return}}catch{}try{xe(r)}catch{}}function Sn(e,t,n={}){let r=n.timeoutMs??15e3,i=Q(e,t,n.prefix),a=Date.now()+r,o=new Int32Array(new SharedArrayBuffer(4));for(;Date.now()<a;){try{be(i)}catch{return!0}Atomics.wait(o,0,0,100)}return!1}export{Vt as API_IMAGE_DIMENSION_LIMIT_PX,we as AgentError,z as CLAUDE_TO_OTTO_TOOL,b as CodedError,pn as DEFAULT_FILE_LOCK_TIMEOUT_MS,t as EventBus,C as InvariantError,j as LARGE_FILE_BYTE_THRESHOLD,Te as McpError,x as NetworkError,S as OAuthError,Ht as PROVIDER_IMAGE_INLINE_MAX_BYTES,Ce as ProviderError,e as TypedEventEmitter,_n as acquireFileLock,bn as acquireFileLockSync,Pe as attachLogListener,bt as buildAllowedEnv,yt as checkShellCommand,L as createDispatcher,Be as createLogger,Tt as createPkcePair,rt as createProjectOverflowLogPath,nt as createTempLoggerPath,Ue as exists,Je as formatBytes,H as generateChallenge,Et as generateState,V as generateVerifier,dt as getDefaultProxy,$e as getHomeDir,F as getProjectDir,tt as getThirdPartyToolBinaryDir,et as getThirdPartyToolDir,_t as headerGet,ft as installGlobalProxyDispatcher,w as invariant,We as isDirectory,Ge as isFile,an as isStartupTraceEnabled,Le as isTransportInitialized,Q as lockPath,wt as mapClaudeAgentToolNames,xt as mapClaudeToolName,tn as markStartupPhase,q as matchSubsequence,lt as matchesGlobPattern,Ve as mime,He as mkdirp,c as normalizePath,It as openBrowser,Ct as ottoToClaudeToolName,zt as parseFrontmatterFields,Bt as parseFrontmatterList,st as parseJsonc,ln as positionsToHighlightRanges,Gt as probeImageDimensions,pt as probeProxy,J as rankCandidates,fn as rankLabeledItems,dn as rankNamedItems,Ke as readFileCapped,vn as releaseFileLock,xn as releaseFileLockSync,ht as request,ct as safeStringify,cn as scoreSubsequence,ut as setDefaultProxy,Ie as setLogLevel,Rt as splitFrontmatter,Ft as startLoopbackServer,gt as stream,at as sweepStaleProjectOverflowLogs,it as sweepStaleTempLogs,qe as toTruncationMeta,nn as traceStartupPhase,rn as traceStartupPhaseSync,Ye as truncateHead,Qe as truncateLine,Xe as truncateTail,yn as waitForFileLockRelease,Sn as waitForFileLockReleaseSync};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@x-otto/shared",
|
|
3
|
-
"version": "0.1.0-alpha.
|
|
3
|
+
"version": "0.1.0-alpha.2",
|
|
4
4
|
"files": [
|
|
5
5
|
"dist"
|
|
6
6
|
],
|
|
@@ -22,15 +22,8 @@
|
|
|
22
22
|
"registry": "https://registry.npmjs.org",
|
|
23
23
|
"tag": "alpha"
|
|
24
24
|
},
|
|
25
|
-
"scripts": {
|
|
26
|
-
"build": "tsdown && rm -f dist/*.map && sed -i '' '\\|//# sourceMappingURL=|d' dist/*.js dist/browser/index.js 2>/dev/null; true",
|
|
27
|
-
"typecheck:project": "tsc -p tsconfig.json --noEmit",
|
|
28
|
-
"typecheck:file": "tsc src/index.ts --noEmit --target ES2024 --module ESNext --moduleResolution bundler --esModuleInterop --skipLibCheck",
|
|
29
|
-
"typecheck": "tsc --noEmit",
|
|
30
|
-
"clean": "rm -rf dist"
|
|
31
|
-
},
|
|
32
25
|
"dependencies": {
|
|
33
|
-
"@x-otto/env": "
|
|
26
|
+
"@x-otto/env": "0.1.0-alpha.2",
|
|
34
27
|
"eventsource-parser": "3.0.6",
|
|
35
28
|
"jsonc-parser": "3.3.1",
|
|
36
29
|
"mime-types": "3.0.2",
|
|
@@ -42,5 +35,12 @@
|
|
|
42
35
|
},
|
|
43
36
|
"devDependencies": {
|
|
44
37
|
"@types/mime-types": "3.0.1"
|
|
38
|
+
},
|
|
39
|
+
"scripts": {
|
|
40
|
+
"build": "tsdown && rm -f dist/*.map && sed -i '' '\\|//# sourceMappingURL=|d' dist/*.js dist/browser/index.js 2>/dev/null; true",
|
|
41
|
+
"typecheck:project": "tsc -p tsconfig.json --noEmit",
|
|
42
|
+
"typecheck:file": "tsc src/index.ts --noEmit --target ES2024 --module ESNext --moduleResolution bundler --esModuleInterop --skipLibCheck",
|
|
43
|
+
"typecheck": "tsc --noEmit",
|
|
44
|
+
"clean": "rm -rf dist"
|
|
45
45
|
}
|
|
46
|
-
}
|
|
46
|
+
}
|