durebak 0.1.0-alpha.2 → 0.1.0-alpha.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/README.md +13 -5
  2. package/SECURITY.md +2 -1
  3. package/dist/bridge-heartbeat.d.ts +14 -0
  4. package/dist/bridge-heartbeat.js +49 -0
  5. package/dist/cli.js +82 -5
  6. package/dist/client.d.ts +4 -2
  7. package/dist/client.js +2 -2
  8. package/dist/codex-owned-host.d.ts +26 -0
  9. package/dist/codex-owned-host.js +190 -0
  10. package/dist/codex-rpc.d.ts +36 -0
  11. package/dist/codex-rpc.js +142 -0
  12. package/dist/codex-turns.d.ts +101 -0
  13. package/dist/codex-turns.js +207 -0
  14. package/dist/collaboration-status.d.ts +38 -0
  15. package/dist/collaboration-status.js +14 -0
  16. package/dist/continuations.d.ts +36 -0
  17. package/dist/continuations.js +103 -0
  18. package/dist/database.js +28 -5
  19. package/dist/doctor.d.ts +17 -16
  20. package/dist/doctor.js +33 -9
  21. package/dist/execution-driver.d.ts +165 -0
  22. package/dist/execution-driver.js +233 -0
  23. package/dist/harnesses/catalog.d.ts +28 -0
  24. package/dist/harnesses/catalog.js +16 -0
  25. package/dist/health.d.ts +23 -0
  26. package/dist/health.js +12 -0
  27. package/dist/managed-control.d.ts +128 -0
  28. package/dist/managed-control.js +119 -0
  29. package/dist/mcp.js +58 -1
  30. package/dist/message-queue.d.ts +7 -0
  31. package/dist/message-queue.js +58 -0
  32. package/dist/migrations.d.ts +1 -1
  33. package/dist/migrations.js +189 -1
  34. package/dist/native-bootstrap-sandbox.d.ts +10 -0
  35. package/dist/native-bootstrap-sandbox.js +83 -0
  36. package/dist/native-peer-inspector.d.ts +29 -0
  37. package/dist/native-peer-inspector.js +131 -0
  38. package/dist/native-profile-fence.d.ts +29 -0
  39. package/dist/native-profile-fence.js +142 -0
  40. package/dist/opencode-http.d.ts +15 -0
  41. package/dist/opencode-http.js +143 -0
  42. package/dist/opencode-outcomes.d.ts +10 -0
  43. package/dist/opencode-outcomes.js +72 -0
  44. package/dist/opencode-owned-host.d.ts +41 -0
  45. package/dist/opencode-owned-host.js +230 -0
  46. package/dist/opencode-readiness.d.ts +8 -0
  47. package/dist/opencode-readiness.js +32 -0
  48. package/dist/opencode-turns.d.ts +130 -0
  49. package/dist/opencode-turns.js +238 -0
  50. package/dist/owned-native-command.d.ts +20 -0
  51. package/dist/owned-native-command.js +92 -0
  52. package/dist/owned-peer-connector.d.ts +19 -0
  53. package/dist/owned-peer-connector.js +79 -0
  54. package/dist/protected-tasks.d.ts +37 -0
  55. package/dist/protected-tasks.js +87 -0
  56. package/dist/request-preview.d.ts +55 -0
  57. package/dist/request-preview.js +77 -0
  58. package/dist/requests.d.ts +250 -0
  59. package/dist/requests.js +303 -0
  60. package/dist/runtime.d.ts +190 -0
  61. package/dist/runtime.js +138 -6
  62. package/dist/scoped-attachments.d.ts +92 -0
  63. package/dist/scoped-attachments.js +75 -0
  64. package/dist/setup.d.ts +4 -0
  65. package/dist/setup.js +1 -1
  66. package/dist/skill-content.d.ts +3 -0
  67. package/dist/skill-content.js +125 -0
  68. package/dist/skills.d.ts +14 -0
  69. package/dist/skills.js +82 -0
  70. package/dist/store.d.ts +469 -0
  71. package/dist/store.js +109 -52
  72. package/dist/update-cli.d.ts +18 -0
  73. package/dist/update-cli.js +86 -0
  74. package/dist/update-scheduler.d.ts +19 -0
  75. package/dist/update-scheduler.js +109 -0
  76. package/dist/update-state.d.ts +74 -0
  77. package/dist/update-state.js +158 -0
  78. package/dist/update-trust.d.ts +30 -0
  79. package/dist/update-trust.js +52 -0
  80. package/dist/updates.d.ts +29 -0
  81. package/dist/updates.js +105 -0
  82. package/dist/verification.d.ts +245 -0
  83. package/dist/verification.js +113 -0
  84. package/dist/work-input.d.ts +97 -0
  85. package/dist/work-input.js +83 -0
  86. package/dist/work-reservations.d.ts +56 -0
  87. package/dist/work-reservations.js +169 -0
  88. package/docs/USAGE.md +117 -1
  89. package/package.json +3 -3
package/README.md CHANGED
@@ -6,11 +6,13 @@ Local, durable collaboration between coding-agent sessions. Experimental alpha f
6
6
 
7
7
  두레박은 같은 컴퓨터의 코딩 에이전트 세션이 메시지·작업·결과를 주고받는 로컬 협업 런타임입니다. 각 세션은 자기 호스트와 맥락을 유지하고, CLI 또는 MCP로 참여합니다.
8
8
 
9
- **현재 버전: 0.1.0-alpha.2, Cooperative 모드.** SQLite 저장소, 인증된 loopback 서버, CLI, MCP stdio bridge가 구현되어 있습니다. 실제 MCP 프로세스 간 통신을 테스트했으며, 호스트별 실제 시험 결과와 제약은 [호스트 테스트](docs/HOST-TESTING.md)에 기록합니다. 자동 세션 실행·깨우기와 반복 작업 스케줄러는 후속 기능입니다.
9
+ **현재 소스: 0.1.0-alpha.24. 사용자용 협업은 Cooperative 모드입니다.** SQLite 저장소, 인증된 loopback 서버, CLI, MCP stdio bridge가 구현되어 있습니다. 실제 MCP 프로세스 간 통신을 테스트했으며, 호스트별 실제 시험 결과와 제약은 [호스트 테스트](docs/HOST-TESTING.md)에 기록합니다. 요청별 대화·기한·취소 notice·checkpoint, 공유 preview, 보호 작업·비공개 텍스트 첨부, revision별 자기보고 검증·재검증과 CLI 협업 화면을 제공합니다. 내부 실험용 Codex·OpenCode 소유 호스트와 실행 ledger, 비동기 준비 상태 검사도 개발 중입니다. 이 내부 구성의 실제 모델 실행·controller 연결·자동 깨우기는 아직 검증하지 않았습니다. 자동 세션 실행·깨우기와 반복 작업 스케줄러는 후속 기능입니다.
10
+
11
+ npm·GitHub 설치/업데이트 경로, 릴리스 구독과 alpha.24의 `update-check`·opt-in 알림은 [설치·업데이트 안내](https://github.com/ggujunhi247/durebak/blob/main/docs/INSTALLATION.md)를 참고하세요.
10
12
 
11
13
  ## 시작하기
12
14
 
13
- Node.js 24 이상과 npm이 필요합니다.
15
+ macOS 또는 Linux, Node.js 24 이상과 npm이 필요합니다. Windows는 이 alpha에서 지원하지 않습니다. Windows CI의 ACL·SQLite 조사는 지원 준비를 위한 시험이며, 제품 실행 검증과 구분합니다.
14
16
 
15
17
  `npx`로 alpha 버전을 실행할 수 있습니다.
16
18
 
@@ -19,7 +21,7 @@ npx --yes durebak@alpha --help
19
21
  npx --yes durebak@alpha serve
20
22
  ```
21
23
 
22
- 재현 가능한 설치에는 `durebak@0.1.0-alpha.2`처럼 정확한 버전을 지정하세요. 서버는 foreground에서 실행하며 Ctrl-C로 종료합니다.
24
+ npm dist-tag와 현재 소스 버전은 다를 수 있습니다. `npm view durebak dist-tags`로 게시 버전을 확인하고 정확한 버전을 지정하세요. 새 후보의 npm 게시가 막힌 경우 [GitHub Releases](https://github.com/ggujunhi247/durebak/releases)의 검증된 `.tgz`와 `SHA256SUMS`를 확인해 `npm install --global ./durebak-VERSION.tgz`로 설치할 수 있습니다. 서버는 foreground에서 실행하며 Ctrl-C로 종료합니다.
23
25
 
24
26
  `git`에서 직접 실행하려면:
25
27
 
@@ -38,7 +40,8 @@ node dist/cli.js serve
38
40
 
39
41
  - 실제 Codex → Codex 요청·검토·결과 제출을 검증했습니다.
40
42
  - Claude Code·OpenCode 설정 어댑터와 6방향 시험 도구를 제공합니다. **이종 모델 간 실통신 성공은 아직 검증하지 못했습니다.**
41
- - 자동 테스트와 실제 MCP 프로세스 왕복 검사를 통과했습니다. [Linux·macOS 원격 CI](https://github.com/ggujunhi247/durebak/actions/runs/36610450906)에서도 테스트와 패키지 검사를 통과했습니다.
43
+ - 자동 테스트와 실제 MCP 프로세스 왕복 검사를 통과했습니다. [Linux·macOS 원격 CI](https://github.com/ggujunhi247/durebak/actions)에서도 테스트와 패키지 검사를 통과했습니다.
44
+ - `durebak dashboard --session FILE`에서 원문 없이 연락·요청·검증 상태를 확인합니다. bridge 접촉은 실제 host 준비 증거가 아닙니다.
42
45
  - 자동 세션 깨우기·네이티브 대화 재개·무인 반복 개선은 아직 지원하지 않습니다.
43
46
 
44
47
  자세한 버전과 제한은 [호환성](docs/COMPATIBILITY.md)을 확인하세요.
@@ -80,11 +83,16 @@ npm run lab
80
83
  | 개발·테스트 | [기여 안내](CONTRIBUTING.md) · [구현 현황](docs/IMPLEMENTATION.md) · [구조](docs/ARCHITECTURE.md) |
81
84
  | 실제 호스트 시험 | [호스트 테스트](docs/HOST-TESTING.md) |
82
85
  | 릴리스 관리 | [배포 절차](docs/RELEASING.md) · [변경점](CHANGELOG.md) |
86
+ | 성능 측정과 한계 | [큐 성능](docs/PERFORMANCE.md) |
83
87
 
84
88
  ## 배포
85
89
 
86
- [Apache-2.0](LICENSE) 라이선스의 실험적 알파입니다. 소스 저장소는 [ggujunhi247/durebak](https://github.com/ggujunhi247/durebak)이며 **npm에는 아직 게시하지 않았습니다.** 현재는 위의 소스 설치 방법을 사용하세요. npm 배포 설정은 공개 `alpha` 채널용으로 준비되어 있습니다. 설정 준비와 실제 registry 게시는 별개이며, 게시 완료 전에는 위 소스 설치 방법을 사용하세요.
90
+ [Apache-2.0](LICENSE) 라이선스의 실험적 알파입니다. 소스 저장소는 [ggujunhi247/durebak](https://github.com/ggujunhi247/durebak)입니다. 검증을 마친 버전의 배포 파일은 [GitHub prerelease](https://github.com/ggujunhi247/durebak/releases)에서 제공합니다. GitHub 배포와 npm 게시는 별개입니다. npm의 현재 게시 버전은 `npm view durebak dist-tags`로 별도 확인하세요. CI/CD는 검증된 동일 artifact를 protected npm environment와 trusted publisher를 통해 게시하도록 구성되어 있으며, 인증·게시권한 확인이 남으면 소스 또는 GitHub 배포 파일을 사용합니다.
87
91
 
88
92
  제품명은 **두레박**, 영문 브랜드와 CLI 식별자는 **Durebak / durebak**입니다.
89
93
 
90
94
  메시지 전달 정책: [큐·중요도·대기·확인 규칙](docs/QUEUE-POLICY.md). 새 클라이언트는 `receive`와 `ack(id,receipt)`를 사용한다.
95
+
96
+ ### 협업 스킬 (개발 소스)
97
+
98
+ `durebak skills --harness all --workspace PROJECT`로 Codex·Claude Code·OpenCode용 공통 협업 안내와 호출 entry point를 설치합니다. Codex는 `$durebak`, Claude Code/OpenCode는 `/durebak`에서 요청·받기·응답·검증을 진행합니다. 각 세션의 별도 MCP/credential 연결은 필요하며 자동 native 깨우기는 아직 지원하지 않습니다. [설치·사용 계약](docs/USAGE.md#협업-스킬과-커맨드-schema10-개발-소스)을 참고하세요.
package/SECURITY.md CHANGED
@@ -8,7 +8,8 @@ The operating-system user is the trust boundary. Session credentials prevent acc
8
8
 
9
9
  - Store data and session credentials outside repositories. Directories must have mode 0700; credential files must have mode 0600.
10
10
  - `connection.json` contains the local address, not the admin credential. `admin.json` is administrative; session tokens are stored hashed in SQLite.
11
- - The database contains plaintext messages, task criteria and artifact contents. Disk encryption and backups are the user's responsibility.
11
+ - The database directory must belong to the effective OS user and prohibit group/other access. Final directory symlinks, including paths ending in `/`, are rejected. The main DB and existing `-wal`, `-shm`, `-journal` must be regular files owned by that user, prohibit group/other access and have a single hardlink. Unsafe files are refused before SQLite opens; newly generated sidecars are rechecked before migration and after initialization. No automatic chmod, chown or recovery-file deletion occurs.
12
+ - The database contains plaintext messages, task criteria and artifact contents. [SQLite WAL and shared-memory files](https://www.sqlite.org/tempfiles.html) also belong to private storage. Disk encryption and backups are the user's responsibility. These startup checks do not provide atomic protection against a hostile process sharing the same OS account, elevated administrators or platform ACL grants beyond POSIX mode bits. Stronger isolation from agent processes requires a separately owned daemon or OS sandbox and a client arrangement that exposes only scoped session API credentials, never the admin credential or DB filesystem access. This release does not configure that deployment; the current CLI/MCP also need their own readable connection metadata and credential files.
12
13
  - Revocation rejects future calls; it cannot undo information already read or stop a host's model/process.
13
14
  - Received messages, artifact text and rendered Markdown are untrusted content, not permission to execute commands, expand scope or disclose secrets.
14
15
  - Cache clearing removes only derived local pages; it preserves original evidence. It does not delete provider-side histories or exported files.
@@ -0,0 +1,14 @@
1
+ export interface HeartbeatDependencies {
2
+ instance: string;
3
+ runtimeInfo(): Promise<{
4
+ daemon_epoch?: string | undefined;
5
+ capabilities?: string[] | undefined;
6
+ }>;
7
+ touch(instance: string, epoch: string): Promise<void>;
8
+ close(instance: string, epoch: string): Promise<void>;
9
+ schedule(fn: () => void, delayMs: number): unknown;
10
+ cancel(handle: unknown): void;
11
+ }
12
+ export declare function startBridgeHeartbeat(deps: HeartbeatDependencies): {
13
+ stop(): Promise<void>;
14
+ };
@@ -0,0 +1,49 @@
1
+ import { DomainError } from './domain.js';
2
+ export function startBridgeHeartbeat(deps) {
3
+ let stopped = false, handle, epoch, failures = 0;
4
+ let pending = Promise.resolve();
5
+ let stopping;
6
+ const schedule = (delay) => { if (!stopped)
7
+ handle = deps.schedule(() => { handle = undefined; pending = run(); }, delay); };
8
+ async function run() {
9
+ try {
10
+ const info = await deps.runtimeInfo();
11
+ if (stopped)
12
+ return;
13
+ if (!info.daemon_epoch || !info.capabilities?.includes('session_health_v1')) {
14
+ schedule(60000);
15
+ return;
16
+ }
17
+ epoch = info.daemon_epoch;
18
+ await deps.touch(deps.instance, epoch);
19
+ if (stopped)
20
+ return;
21
+ failures = 0;
22
+ schedule(10000);
23
+ }
24
+ catch (error) {
25
+ if (error instanceof DomainError && error.code === 'unauthorized') {
26
+ stopped = true;
27
+ return;
28
+ }
29
+ schedule(Math.min(60000, 10000 * 2 ** Math.min(failures++, 3)));
30
+ }
31
+ }
32
+ pending = run();
33
+ return { stop() {
34
+ if (stopping)
35
+ return stopping;
36
+ stopped = true;
37
+ if (handle !== undefined) {
38
+ deps.cancel(handle);
39
+ handle = undefined;
40
+ }
41
+ stopping = (async () => { await pending; if (epoch) {
42
+ try {
43
+ await deps.close(deps.instance, epoch);
44
+ }
45
+ catch { /* Contact expiry remains authoritative if graceful close fails. */ }
46
+ } })();
47
+ return stopping;
48
+ } };
49
+ }
package/dist/cli.js CHANGED
@@ -1,7 +1,11 @@
1
1
  #!/usr/bin/env node
2
+ import { handleUpdateCommand, updateCommandContext, cachedUpdateNotice } from './update-cli.js';
3
+ import { managedBindSchema } from './managed-control.js';
2
4
  import { resolveHarness, legacyProvider } from './harnesses/registry.js';
5
+ import { harnessCatalog } from './harnesses/catalog.js';
3
6
  import { version } from './version.js';
4
7
  import { createSetup } from './setup.js';
8
+ import { installSkills } from './skills.js';
5
9
  import { doctor } from './doctor.js';
6
10
  import { parseArgs } from 'node:util';
7
11
  import { openSync, closeSync, writeFileSync, unlinkSync, realpathSync, readFileSync } from 'node:fs';
@@ -11,16 +15,27 @@ import { credential, adminCall, dataDirectory, sessionCall } from './client.js';
11
15
  import { DomainError, fail, hash } from './domain.js';
12
16
  import { startRuntime, operations } from './runtime.js';
13
17
  import { serveMcp } from './mcp.js';
18
+ import { renderCollaborationStatus } from './collaboration-status.js';
14
19
  import { exportRecord } from './records.js';
15
20
  import { storagePaths, managedCredentialPath, managedRecordPath } from './paths.js';
16
21
  const help = `Durebak ${version} — local cooperative session bus
17
22
 
23
+ durebak update-check [--channel alpha|beta|rc|stable] Read published update candidates
24
+ durebak update status|disable|unpin [--update-dir PATH]
25
+ durebak update enable --mode notify --channel alpha|beta|rc|stable
26
+ durebak update pin VERSION Pin notification policy version
27
+ durebak update apply --version VERSION Report blocked automatic-apply prerequisites
28
+ durebak harnesses Read harness capability evidence (no host execution)
18
29
  durebak serve [--data-dir PATH] Run loopback daemon in foreground
19
30
  durebak register --workspace PATH --alias NAME --harness codex|claude-code|opencode|other [--out FILE] [--data-dir PATH]
20
31
  durebak revoke SESSION_ID [--data-dir PATH] Revoke a session credential
21
32
  durebak mcp --session FILE Start session-scoped MCP stdio bridge
22
33
  durebak call OPERATION --session FILE [--json JSON | --input FILE]
34
+ durebak skills --harness codex|claude-code|opencode|all --workspace PATH Install project skill/command without credentials
23
35
  durebak setup --harness codex|claude-code|opencode --session FILE --out FILE
36
+ durebak managed-bind SESSION_ID --harness codex --native-id ID --profile PROFILE --instance ID --key KEY --out FILE [--data-dir PATH]
37
+ durebak managed-policy --json JSON [--data-dir PATH] Administrator-only policy configuration (no host execution)
38
+ durebak dashboard --session FILE Show one read-only cooperation snapshot
24
39
  durebak doctor --session FILE Check identity and runtime compatibility
25
40
  durebak export TASK_ID --session FILE [--out FILE]
26
41
  durebak paths [--session FILE | --data-dir PATH] Show local storage paths
@@ -36,11 +51,15 @@ const output = (value) => process.stdout.write(JSON.stringify(value) + '\n');
36
51
  function required(value, name) { if (!value)
37
52
  fail(`missing_${name}`); return value; }
38
53
  async function main() {
39
- const { values, positionals } = parseArgs({ allowPositionals: true, options: {
40
- 'data-dir': { type: 'string' }, workspace: { type: 'string' }, alias: { type: 'string' }, provider: { type: 'string' }, harness: { type: 'string' }, out: { type: 'string' }, session: { type: 'string' }, json: { type: 'string' }, input: { type: 'string' }, host: { type: 'string' }, help: { type: 'boolean' }, version: { type: 'boolean' },
41
- } });
54
+ const options = {
55
+ 'update-dir': { type: 'string' }, channel: { type: 'string' }, mode: { type: 'string' }, 'native-id': { type: 'string' }, profile: { type: 'string' }, instance: { type: 'string' }, key: { type: 'string' }, 'data-dir': { type: 'string' }, workspace: { type: 'string' }, alias: { type: 'string' }, provider: { type: 'string' }, harness: { type: 'string' }, out: { type: 'string' }, session: { type: 'string' }, json: { type: 'string' }, input: { type: 'string' }, host: { type: 'string' }, help: { type: 'boolean' },
56
+ };
57
+ // Resolve subcommands while respecting values of options placed before them.
58
+ const preliminary = parseArgs({ allowPositionals: true, strict: false, options });
59
+ const applying = preliminary.positionals[0] === 'update' && preliminary.positionals[1] === 'apply';
60
+ const { values, positionals } = parseArgs({ allowPositionals: true, options: { ...options, version: { type: applying ? 'string' : 'boolean' } } });
42
61
  const command = positionals[0];
43
- if (values.version) {
62
+ if (values.version === true) {
44
63
  process.stdout.write(version + '\n');
45
64
  return;
46
65
  }
@@ -48,6 +67,27 @@ async function main() {
48
67
  process.stdout.write(help);
49
68
  return;
50
69
  }
70
+ if (command === 'update' || command === 'update-check') {
71
+ output(await handleUpdateCommand(command === 'update-check' ? 'check' : positionals[1] ?? 'status', positionals.slice(command === 'update-check' ? 1 : 2), { ...(values.mode === undefined ? {} : { mode: values.mode }), ...(values.channel === undefined ? {} : { channel: values.channel }), ...(typeof values.version === 'string' ? { target: values.version } : {}) }, updateCommandContext(values['update-dir'])));
72
+ return;
73
+ }
74
+ if (process.stderr.isTTY && command !== 'mcp' && ['skills', 'harnesses', 'paths', 'serve', 'register', 'revoke', 'setup', 'managed-bind', 'managed-policy', 'dashboard', 'doctor', 'call', 'export'].includes(command)) {
75
+ try {
76
+ const context = updateCommandContext();
77
+ const notice = cachedUpdateNotice(context.directory, version);
78
+ if (notice)
79
+ process.stderr.write(notice);
80
+ }
81
+ catch { /* A stale notification cannot break an unrelated command. */ }
82
+ }
83
+ if (command === 'skills') {
84
+ output(installSkills(required(values.harness, 'harness'), required(values.workspace, 'workspace')));
85
+ return;
86
+ }
87
+ if (command === 'harnesses') {
88
+ output(harnessCatalog());
89
+ return;
90
+ }
51
91
  const selectedDirectory = () => dataDirectory(values['data-dir']);
52
92
  if (command === 'paths') {
53
93
  const session = values.session ?? process.env.DUREBAK_SESSION_FILE;
@@ -84,17 +124,54 @@ async function main() {
84
124
  }
85
125
  return;
86
126
  }
127
+ if (command === 'managed-bind') {
128
+ const directory = selectedDirectory(), input = managedBindSchema.parse({ sessionId: required(positionals[1], 'session_id'), harness: required(values.harness, 'harness'), nativeId: required(values['native-id'], 'native_id'), profile: required(values.profile, 'profile'), instance: required(values.instance, 'instance'), key: required(values.key, 'key') });
129
+ const destination = resolve(required(values.out, 'out')), fd = openSync(destination, 'wx', 0o600);
130
+ let written = false;
131
+ try {
132
+ const result = z.object({ binding: z.object({ id: z.string(), epoch: z.number() }), ownerToken: z.string().nullable() }).parse(await adminCall(directory, '/v1/managed', { operation: 'bind', args: input }));
133
+ if (!result.ownerToken)
134
+ fail('owner_credential_unavailable');
135
+ writeFileSync(fd, JSON.stringify({ data_dir: directory, binding_id: result.binding.id, epoch: result.binding.epoch, owner_token: result.ownerToken }) + '\n');
136
+ written = true;
137
+ output({ binding_id: result.binding.id, owner_credential_file: destination, auto_wake: false, host_readiness: 'unverified' });
138
+ }
139
+ finally {
140
+ closeSync(fd);
141
+ if (!written)
142
+ unlinkSync(destination);
143
+ }
144
+ return;
145
+ }
146
+ if (command === 'managed-policy') {
147
+ const text = required(values.json, 'json');
148
+ if (Buffer.byteLength(text) > 131072)
149
+ fail('request_too_large');
150
+ let input;
151
+ try {
152
+ input = JSON.parse(text);
153
+ }
154
+ catch {
155
+ fail('invalid_json');
156
+ }
157
+ output({ policy: await adminCall(selectedDirectory(), '/v1/managed', { operation: 'policy', args: input }), auto_wake: false, host_readiness: 'unverified' });
158
+ return;
159
+ }
87
160
  if (command === 'revoke') {
88
161
  output(await adminCall(selectedDirectory(), '/v1/revoke', { id: required(positionals[1], 'session_id') }));
89
162
  return;
90
163
  }
91
- if (!['setup', 'doctor', 'mcp', 'call', 'export'].includes(command))
164
+ if (!['dashboard', 'setup', 'doctor', 'mcp', 'call', 'export'].includes(command))
92
165
  fail('unknown_command');
93
166
  const file = required(values.session ?? process.env.DUREBAK_SESSION_FILE, 'session');
94
167
  if (command === 'setup') {
95
168
  output(createSetup(resolveHarness(values.harness, values.host), file, required(values.out, 'out')));
96
169
  return;
97
170
  }
171
+ if (command === 'dashboard') {
172
+ process.stdout.write(renderCollaborationStatus(await sessionCall(file, 'collaboration_status', {})));
173
+ return;
174
+ }
98
175
  if (command === 'doctor') {
99
176
  const result = await doctor(file);
100
177
  output(result);
package/dist/client.d.ts CHANGED
@@ -12,6 +12,8 @@ export declare function credential(path: string): {
12
12
  provider: string;
13
13
  };
14
14
  };
15
- export declare function request(directory: string, token: string, path: string, payload: unknown): Promise<unknown>;
15
+ export declare function request(directory: string, token: string, path: string, payload: unknown, options?: {
16
+ timeoutMs?: number;
17
+ }): Promise<unknown>;
16
18
  export declare function sessionCall(file: string, operation: Operation, args: unknown): Promise<unknown>;
17
- export declare function adminCall(directory: string, path: '/v1/register' | '/v1/revoke', args: unknown): Promise<unknown>;
19
+ export declare function adminCall(directory: string, path: '/v1/register' | '/v1/revoke' | '/v1/managed', args: unknown): Promise<unknown>;
package/dist/client.js CHANGED
@@ -11,7 +11,7 @@ export function privateJson(path) {
11
11
  }
12
12
  const credentialSchema = z.object({ data_dir: z.string(), token: z.string().regex(/^[a-f0-9]{64}$/), session: z.object({ id: z.string(), workspace: z.string(), alias: z.string(), provider: z.string() }).passthrough() }).strict();
13
13
  export function credential(path) { return credentialSchema.parse(privateJson(path)); }
14
- export async function request(directory, token, path, payload) {
14
+ export async function request(directory, token, path, payload, options) {
15
15
  const connection = z.object({ url: z.string(), instance: z.string() }).parse(privateJson(join(directory, 'connection.json')));
16
16
  const url = new URL(connection.url);
17
17
  if (url.protocol !== 'http:' || url.hostname !== '127.0.0.1' || !url.port || url.username || url.password || url.pathname !== '/' || url.search || url.hash)
@@ -19,7 +19,7 @@ export async function request(directory, token, path, payload) {
19
19
  const text = JSON.stringify(payload);
20
20
  if (Buffer.byteLength(text) > 131072)
21
21
  fail('request_too_large');
22
- const response = await fetch(new URL(path, url), { method: 'POST', headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' }, body: text, redirect: 'error', signal: AbortSignal.timeout(15000) });
22
+ const response = await fetch(new URL(path, url), { method: 'POST', headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' }, body: text, redirect: 'error', signal: AbortSignal.timeout(options?.timeoutMs ?? 15000) });
23
23
  let resultText = '';
24
24
  let size = 0;
25
25
  const reader = response.body?.getReader();
@@ -0,0 +1,26 @@
1
+ import { z } from 'zod';
2
+ import { CodexTurns } from './codex-turns.js';
3
+ declare const optionsSchema: z.ZodObject<{
4
+ binary: z.ZodString;
5
+ profile: z.ZodString;
6
+ cwd: z.ZodString;
7
+ instance: z.ZodString;
8
+ timeoutMs: z.ZodDefault<z.ZodNumber>;
9
+ shutdownMs: z.ZodDefault<z.ZodNumber>;
10
+ }, z.core.$strict>;
11
+ export type OwnedCodexOptions = z.input<typeof optionsSchema>;
12
+ export declare function startOwnedCodexHost(input: OwnedCodexOptions): Promise<Readonly<{
13
+ metadata: Readonly<{
14
+ profile: string;
15
+ nativeId: string;
16
+ epoch: 1;
17
+ instance: string;
18
+ cli_version: "0.146.0";
19
+ command_scope_verified: true;
20
+ model_verified: false;
21
+ auto_wake: false;
22
+ }>;
23
+ attach(id: string): CodexTurns;
24
+ close: () => Promise<void>;
25
+ }>>;
26
+ export {};
@@ -0,0 +1,190 @@
1
+ import { spawn, execFile } from 'node:child_process';
2
+ import { promisify } from 'node:util';
3
+ import { existsSync, lstatSync, readFileSync, realpathSync, readdirSync, writeFileSync, symlinkSync, unlinkSync, mkdtempSync, rmSync } from 'node:fs';
4
+ import { join } from 'node:path';
5
+ import { tmpdir } from 'node:os';
6
+ import { randomUUID } from 'node:crypto';
7
+ import { z } from 'zod';
8
+ import { fail, short } from './domain.js';
9
+ import { CodexRpc } from './codex-rpc.js';
10
+ import { CodexTurns } from './codex-turns.js';
11
+ import { NativeProfileFence } from './native-profile-fence.js';
12
+ const exec = promisify(execFile), permissionProfile = 'durebak-scoped';
13
+ const optionsSchema = z.object({ binary: z.string().min(1), profile: z.string().min(1), cwd: z.string().min(1), instance: short, timeoutMs: z.number().int().min(10).max(20000).default(20000), shutdownMs: z.number().int().min(10).max(3000).default(1000) }).strict();
14
+ function privateDir(path) { const normalized = path.replace(/\/+$/, '') || '/', stat = lstatSync(normalized); if (stat.isSymbolicLink() || !stat.isDirectory() || (stat.mode & 0o077) !== 0 || stat.uid !== process.getuid?.())
15
+ fail('native_directory_unsafe'); return realpathSync.native(normalized); }
16
+ function configText(cwd) { return `approval_policy = "never"\ndefault_permissions = "${permissionProfile}"\n[permissions.${permissionProfile}.filesystem]\n":minimal" = "read"\n${JSON.stringify(cwd)} = "read"\n[permissions.${permissionProfile}.network]\nenabled = false\n`; }
17
+ async function within(promise, ms) { let timer; try {
18
+ return await Promise.race([promise, new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('native_shutdown_timeout')), ms); })]);
19
+ }
20
+ finally {
21
+ if (timer)
22
+ clearTimeout(timer);
23
+ } }
24
+ function verifyConfig(raw, cwd) {
25
+ const config = z.object({ config: z.object({ approval_policy: z.literal('never'), default_permissions: z.literal(permissionProfile), mcp_servers: z.record(z.string(), z.unknown()), model_providers: z.record(z.string(), z.unknown()), model_provider: z.literal('openai').nullable(), sandbox_mode: z.null(), permissions: z.record(z.string(), z.unknown()) }) }).parse(raw).config;
26
+ const selected = z.object({ extends: z.null().optional(), filesystem: z.record(z.string(), z.unknown()), network: z.object({ enabled: z.literal(false) }) }).parse(config.permissions[permissionProfile]);
27
+ const entries = Object.entries(selected.filesystem).filter(([k, v]) => k !== 'glob_scan_max_depth' || v !== null);
28
+ if (Object.keys(config.mcp_servers).length || Object.keys(config.model_providers).length || entries.length !== 2 || selected.filesystem[':minimal'] !== 'read' || selected.filesystem[cwd] !== 'read')
29
+ fail('native_effective_config_conflict');
30
+ }
31
+ async function verifyCommands(rpc, profile, cwd) {
32
+ const suffix = randomUUID(), token = 'DUREBAK_CANARY_' + suffix, root = mkdtempSync(join(tmpdir(), 'durebak-host-canary-')), allowed = join(cwd, '.durebak-read-' + suffix), outside = join(root, 'outside'), privateFile = join(profile, '.durebak-canary-' + suffix), link = join(cwd, '.durebak-symlink-' + suffix), written = join(cwd, '.durebak-write-' + suffix);
33
+ const owned = [];
34
+ try {
35
+ for (const file of [allowed, outside, privateFile]) {
36
+ writeFileSync(file, token, { mode: 0o600, flag: 'wx' });
37
+ owned.push(file);
38
+ }
39
+ symlinkSync(outside, link);
40
+ owned.push(link);
41
+ const run = async (command) => z.object({ stdout: z.string(), exitCode: z.number().int() }).parse(await rpc.call('command/exec', { command, cwd, permissionProfile, timeoutMs: 5000 }));
42
+ const read = await run(['/bin/cat', allowed]);
43
+ if (read.exitCode !== 0 || read.stdout !== token)
44
+ fail('native_read_scope_unverified');
45
+ for (const file of [outside, privateFile, link])
46
+ if ((await run(['/bin/cat', file])).exitCode === 0)
47
+ fail('native_read_scope_unverified');
48
+ const write = await run(['/usr/bin/touch', written]);
49
+ if (write.exitCode === 0 || existsSync(written))
50
+ fail('native_write_scope_unverified');
51
+ }
52
+ finally {
53
+ for (const file of owned.reverse())
54
+ unlinkSync(file);
55
+ if (existsSync(written))
56
+ unlinkSync(written);
57
+ rmSync(root, { recursive: true, force: true });
58
+ }
59
+ }
60
+ // Only fresh owned hosts are created. This non-model factory verifies command
61
+ // canaries, not all model tool paths, and confers no controller authority.
62
+ export async function startOwnedCodexHost(input) {
63
+ const options = optionsSchema.parse(input);
64
+ if (!['darwin', 'linux'].includes(process.platform))
65
+ fail('native_platform_unsupported');
66
+ const cwd = privateDir(options.cwd), profile = privateDir(options.profile), binary = realpathSync.native(options.binary);
67
+ if (!lstatSync(binary).isFile() || readdirSync(cwd).length)
68
+ fail('native_input_not_empty');
69
+ const configFile = join(profile, 'config.toml'), stat = lstatSync(configFile);
70
+ if (stat.isSymbolicLink() || !stat.isFile() || stat.nlink !== 1 || (stat.mode & 0o077) !== 0 || stat.uid !== process.getuid?.())
71
+ fail('native_profile_config_unsafe');
72
+ if (readFileSync(configFile, 'utf8') !== configText(cwd))
73
+ fail('native_profile_config_mismatch');
74
+ const fence = NativeProfileFence.claim(profile, options.instance), env = { PATH: process.env.PATH ?? '', ...(process.env.HOME ? { HOME: process.env.HOME } : {}), CODEX_HOME: profile };
75
+ let child, rpc, turns, bindingId, closed = false, released = false, groupDisappeared = false, cleanupFailed = false, exited, closing;
76
+ const retire = () => { if (closed)
77
+ return; closed = true; try {
78
+ rpc?.close();
79
+ }
80
+ catch {
81
+ cleanupFailed = true;
82
+ } try {
83
+ turns?.close();
84
+ }
85
+ catch {
86
+ cleanupFailed = true;
87
+ } };
88
+ const release = () => { if (released)
89
+ return; try {
90
+ fence.close();
91
+ released = true;
92
+ }
93
+ catch {
94
+ cleanupFailed = true;
95
+ } };
96
+ const signal = (name) => { if (!child?.pid || groupDisappeared)
97
+ return; try {
98
+ process.kill(-child.pid, name);
99
+ }
100
+ catch (error) {
101
+ if (error.code === 'ESRCH')
102
+ groupDisappeared = true;
103
+ else if (error.code !== 'EPERM')
104
+ throw error;
105
+ } };
106
+ const groupGone = () => { if (!child?.pid || groupDisappeared)
107
+ return true; try {
108
+ process.kill(-child.pid, 0);
109
+ return false;
110
+ }
111
+ catch (error) {
112
+ if (error.code === 'ESRCH') {
113
+ groupDisappeared = true;
114
+ return true;
115
+ }
116
+ if (error.code === 'EPERM')
117
+ return false;
118
+ throw error;
119
+ } };
120
+ const waitForExit = async () => { const deadline = Date.now() + options.shutdownMs; while (!groupGone()) {
121
+ if (Date.now() >= deadline)
122
+ fail('native_shutdown_timeout');
123
+ await new Promise(resolve => setTimeout(resolve, 10));
124
+ } if (exited)
125
+ await within(exited, Math.max(1, deadline - Date.now())); };
126
+ // EPERM can occur during macOS zombie reaping; it remains pending, never gone.
127
+ // Leader exit is insufficient: descendants may close their pipes and ignore TERM.
128
+ // Keep the ownership fence until both the leader and its owned group are gone.
129
+ const close = () => { if (closing)
130
+ return closing; closing = (async () => { retire(); if (!released) {
131
+ if (child && exited) {
132
+ child.stdin.end();
133
+ signal('SIGTERM');
134
+ try {
135
+ await waitForExit();
136
+ }
137
+ catch {
138
+ signal('SIGKILL');
139
+ await waitForExit();
140
+ }
141
+ }
142
+ release();
143
+ } if (cleanupFailed)
144
+ fail('native_cleanup_unknown'); })(); const pending = closing; void pending.catch(() => { if (closing === pending)
145
+ closing = undefined; }); return pending; };
146
+ try {
147
+ const version = await exec(binary, ['--version'], { cwd, env, timeout: 5000, maxBuffer: 4096, killSignal: 'SIGKILL' });
148
+ if (version.stdout.trim() !== 'codex-cli 0.146.0')
149
+ fail('native_version_unsupported');
150
+ child = spawn(binary, ['app-server', '--listen', 'stdio://'], { cwd, env, detached: true, stdio: ['pipe', 'pipe', 'pipe'] });
151
+ exited = new Promise(resolve => { child.once('close', () => { retire(); resolve(); void close().catch(() => { }); }); });
152
+ child.once('exit', () => { retire(); void close().catch(() => { }); });
153
+ child.on('error', () => rpc?.close());
154
+ child.stderr.resume();
155
+ rpc = new CodexRpc(child.stdout, child.stdin, { timeoutMs: options.timeoutMs });
156
+ await rpc.call('initialize', { clientInfo: { name: 'durebak_owned', version: '0.1.0-alpha.16' }, capabilities: { experimentalApi: true } });
157
+ rpc.notify('initialized', {});
158
+ const loaded = z.object({ data: z.array(z.string()) }).parse(await rpc.call('thread/loaded/list', {}));
159
+ if (loaded.data.length)
160
+ fail('native_host_not_fresh');
161
+ verifyConfig(await rpc.call('config/read', { includeLayers: false }), cwd);
162
+ const started = z.object({ thread: z.object({ id: short, cliVersion: z.literal('0.146.0'), cwd: z.string(), modelProvider: z.literal('openai'), ephemeral: z.literal(false), status: z.object({ type: z.literal('idle') }) }), cwd: z.string(), modelProvider: z.literal('openai'), approvalPolicy: z.literal('never'), activePermissionProfile: z.object({ id: z.literal(permissionProfile) }), instructionSources: z.array(z.unknown()) }).parse(await rpc.call('thread/start', { cwd, permissions: permissionProfile, approvalPolicy: 'never', ephemeral: false }));
163
+ if (realpathSync.native(started.cwd) !== cwd || realpathSync.native(started.thread.cwd) !== cwd || started.instructionSources.length)
164
+ fail('native_thread_scope_conflict');
165
+ fence.recordNative(started.thread.id);
166
+ const mcp = z.object({ data: z.array(z.unknown()), nextCursor: z.null() }).parse(await rpc.call('mcpServerStatus/list', { limit: 100 }));
167
+ if (mcp.data.length)
168
+ fail('native_mcp_scope_conflict');
169
+ await verifyCommands(rpc, profile, cwd);
170
+ if (closed)
171
+ fail('native_host_closed');
172
+ const metadata = Object.freeze({ profile, nativeId: started.thread.id, epoch: 1, instance: options.instance, cli_version: '0.146.0', command_scope_verified: true, model_verified: false, auto_wake: false });
173
+ const ownedRpc = rpc;
174
+ return Object.freeze({ metadata, attach(id) { short.parse(id); if (closed)
175
+ fail('native_host_closed'); if (bindingId && id !== bindingId)
176
+ fail('native_binding_conflict'); if (!turns) {
177
+ turns = new CodexTurns(fence, ownedRpc, { binding: { bindingId: id, profile, nativeId: metadata.nativeId, epoch: 1, instance: options.instance }, cwd, permissionProfile });
178
+ bindingId = id;
179
+ } return turns; }, close });
180
+ }
181
+ catch {
182
+ try {
183
+ await close();
184
+ }
185
+ catch {
186
+ fail('native_shutdown_unknown');
187
+ }
188
+ fail('native_host_bootstrap_failed');
189
+ }
190
+ }
@@ -0,0 +1,36 @@
1
+ import type { Readable, Writable } from 'node:stream';
2
+ export interface RpcNotification {
3
+ method: string;
4
+ params?: unknown;
5
+ }
6
+ interface Options {
7
+ timeoutMs?: number;
8
+ maxLineBytes?: number;
9
+ maxPending?: number;
10
+ onNotification?: (message: RpcNotification) => void;
11
+ }
12
+ export declare class CodexRpc {
13
+ private input;
14
+ private output;
15
+ private options;
16
+ private pending;
17
+ private sequence;
18
+ private buffer;
19
+ private closed;
20
+ private readonly timeoutMs;
21
+ private readonly maxLineBytes;
22
+ private readonly maxPending;
23
+ constructor(input: Readable, output: Writable, options?: Options);
24
+ private terminate;
25
+ private end;
26
+ private readError;
27
+ private writeError;
28
+ private write;
29
+ private message;
30
+ private data;
31
+ call(method: string, params: unknown): Promise<unknown>;
32
+ notify(method: string, params: unknown): void;
33
+ private detach;
34
+ close(): void;
35
+ }
36
+ export {};