@ngockhoale/ckit 0.2.2 → 0.2.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/README.md CHANGED
@@ -17,7 +17,7 @@ No env file and no API key are needed: every agent uses the login of its own CLI
17
17
 
18
18
  ## Agent Company (team mode)
19
19
 
20
- A Director plus Team BA (2 agents discuss, then write one handoff) → Team Implement → Team QC (2 reviewers; FAIL returns to Implement, up to `limits.qcLoops`) → (optional) Director review against your original request → Director delivery report. Inside a team the agents discuss in bounded rounds (`limits.baRounds`, early stop on AGREED), the lead writes one `### HANDOFF` (DONE / DECISIONS / OPEN / FOR YOU) and the next team gets it in full. Before any team starts the Director triages the request (PROCEED / NEED INFO, up to 3 rounds, no turns are spent while it waits for you / CANNOT DO, shown as `declined`); runs live only in the CKit process that started them, so a run waiting for your answer is not resumed after a restart and shows in Runs as interrupted. You always talk to the Director; it can continue, redirect or stop the run.
20
+ A Director plus Team BA (2 agents discuss, then write one handoff) → Team Implement → Team QC (2 reviewers; FAIL returns to Implement, up to `limits.qcLoops`) → (optional) Director review against your original request → Director delivery report. Inside a team the agents discuss in bounded rounds (`limits.baRounds`, early stop on AGREED), the lead writes one `### HANDOFF` (DONE / DECISIONS / OPEN / FOR YOU) and the next team gets it in full. Before any team starts the Director triages the request (PROCEED / NEED INFO, up to 3 rounds, no turns are spent while it waits for you / CANNOT DO, shown as `declined`); runs live only in the CKit process that started them, so a run waiting for your answer is not resumed after a restart and shows in Runs as interrupted. You always talk to the Director; it can continue, redirect or stop the run. When a team asks the Director something only you can decide, the Director passes it on (at most 3 times per run): the run pauses, the question appears in the conversation and the request box turns into an amber ANSWER box (text, attached files and `@` mentions all work; "Proceed with assumptions" uses the Director's stated assumption).
21
21
 
22
22
  ```bash
23
23
  ckit # no command, in a terminal: opens the GUI. First time in a project it lands on Config so setup is done there
@@ -28,7 +28,7 @@ ckit team --demo # same pipeline in the terminal, fully SIMULATED (no mo
28
28
  ckit team "<goal>" # real run with the agents in <project>/.ckit/team.json (codex / claude-code / omp / api)
29
29
  ckit team --init # write the default .ckit/team.json (--force overwrites)
30
30
  ```
31
- - Teams are configurable in Config: only the Director is mandatory; BA, Implement and QC can each be removed or re-added, and `+ Add team` creates your own team (`extraTeams` in `.ckit/team.json`: name, mission, agents). All teams follow one numbered flow, `order` (e.g. `["ba","implement","test","qc"]`, reorder with the arrows in Config; absent = ba, implement, qc with custom teams placed by the old `runAfter`): work goes Director -> team 1 -> team 2 ..., each team gets the Director's brief and the previous team's output. A team can end its message with `ASK PREVIOUS: <question>` (the team before it, or the Director, answers) or `RETURN TO PREVIOUS: <reason>` (QC's FAIL means the same); both are limited to `limits.qcLoops` per team boundary ("Max send-backs per team"). Each agent (Director too) also has an optional `cliArgs` text box ("Extra CLI arguments"), e.g. `--settings ./other-settings.json`: it is split like a shell would (quotes group, no `~` or `$VAR` expansion), appended to that agent's start command after CKit's own flags and before the prompt, and empty means not used.
31
+ - Teams are configurable in Config: only the Director is mandatory; BA, Implement and QC can each be removed or re-added, and `+ Add team` creates your own team (`extraTeams` in `.ckit/team.json`: name, mission, agents). All teams follow one numbered flow, `order` (e.g. `["ba","implement","test","qc"]`, reorder with the arrows in Config; absent = ba, implement, qc with custom teams placed by the old `runAfter`): work goes Director -> team 1 -> team 2 ..., each team gets the Director's brief and the previous team's output. A team can end its message with `ASK PREVIOUS: <question>` (the team before it, or the Director, answers) or `RETURN TO PREVIOUS: <reason>` (QC's FAIL means the same); both are limited to `limits.qcLoops` per team boundary ("Max send-backs per team"). Each agent (Director too) also has an optional `cliArgs` text box ("Extra CLI arguments"), e.g. `--settings ./other-settings.json`: it is split like a shell would (quotes group; `~` and `$HOME` become your home folder, other `$VAR` are not expanded), appended to that agent's start command after CKit's own flags and before the prompt, and empty means not used.
32
32
 
33
33
  Every run is journaled to `.ckit/team/runs/<runId>/` (`events.jsonl`, `handoff-ba.md`, `qc-report-N.md`, `transcript.md`, `report.md`). Real agents use their own CLI login; codex runs `read-only` unless the agent has `access: "write"` (then `workspace-write`), claude uses `acceptEdits` only for write access, never bypass.
34
34
 
@@ -67,9 +67,9 @@ the exact shape the UI will consume. ADR-016 records the hand-written state mach
67
67
 
68
68
  ## Honesty gates (do not remove)
69
69
 
70
- - Published as `@ngockhoale/ckit`; publish only on the owner's request, after `npm test` passes.
70
+ - Published as `@ngockhoale/ckit`; a release (version bump, git push with tag, npm publish) follows every finished task that changed source code, and only after `npm test` passes (owner's standing instruction, 2026-11-15).
71
71
  - Simulated adapter output must stay labeled `simulated`; live evidence requires a `live` provenance ref.
72
72
  - Unknown external outcomes stop the flow (`needsReconciliation`); the core never blind-resends.
73
73
 
74
74
 
75
- Optional project-wide `systemPrompt` (Config, "System prompt (optional)") is sent to every agent; empty means prompts are unchanged. Each prompt box has an Enhance button that shows a proposal next to your text and applies it only when you press "Use this". Optional `lanes` (`[{id, name, when, order}]`) let the Director pick which teams a request needs (it answers `LANE: <id>`; the owner can fix a lane in the composer); without lanes the single `order` flow runs as before.
75
+ Optional project-wide `systemPrompt` (Config, "System prompt (optional)") is sent to every agent; empty means prompts are unchanged. Each prompt box has an Enhance button that shows a proposal next to your text and applies it only when you press "Use this". The request box has the same: `✦ Enhance` rewrites your request into a clear brief (goal, requirements, done-when, open points with assumptions) using the Director's CLI, and nothing starts until you press Start. Typing `@` in the request box lists the files and folders of the workspace; the chosen one is inserted as `@relative/path` (names only; dependency, build and VCS folders and secret-looking files are not listed). Optional `lanes` (`[{id, name, when, order}]`) let the Director pick which teams a request needs (it answers `LANE: <id>`; the owner can fix a lane in the composer); without lanes the single `order` flow runs as before.
@@ -0,0 +1,8 @@
1
+ export interface FileEntry {
2
+ readonly path: string;
3
+ readonly dir: boolean;
4
+ }
5
+ /** Breadth-first listing of `root` (relative POSIX paths). Skips dependency/build/VCS folders, secret-looking files and symlinks; bounded in size and depth. */
6
+ export declare function listWorkspace(root: string, max?: number): FileEntry[];
7
+ /** Best matches for what was typed after "@". Empty query = the top level. Lower score is better; ties go to the shorter path. Pure. */
8
+ export declare function searchFiles(entries: readonly FileEntry[], query: string, limit?: number): FileEntry[];
@@ -0,0 +1,65 @@
1
+ // File and folder names of the workspace for "@" mentions in the request box. Names only: no file content is ever read here.
2
+ import { readdirSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ const SKIP_DIRS = new Set(['.git', 'node_modules', '.ckit', '.cache', 'dist', 'build', 'coverage', '.next', '.nuxt', '.turbo', '.venv', 'venv', '__pycache__', '.idea', '.gradle', 'target', '.DS_Store']);
5
+ const SECRET_FILE = /^\.env(\..*)?$|\.(pem|key|p12|pfx)$|^id_(rsa|ed25519|ecdsa)$/i;
6
+ const MAX_ENTRIES = 20_000, MAX_DEPTH = 10;
7
+ /** Breadth-first listing of `root` (relative POSIX paths). Skips dependency/build/VCS folders, secret-looking files and symlinks; bounded in size and depth. */
8
+ export function listWorkspace(root, max = MAX_ENTRIES) {
9
+ const out = [];
10
+ let level = [''];
11
+ for (let depth = 0; depth < MAX_DEPTH && level.length && out.length < max; depth++) {
12
+ const next = [];
13
+ for (const rel of level) {
14
+ let items;
15
+ try {
16
+ items = readdirSync(join(root, rel), { withFileTypes: true });
17
+ }
18
+ catch {
19
+ continue;
20
+ }
21
+ items.sort((a, b) => a.name.localeCompare(b.name));
22
+ for (const it of items) {
23
+ if (out.length >= max)
24
+ break;
25
+ if (it.isSymbolicLink() || /[\r\n\0]/.test(it.name))
26
+ continue;
27
+ const p = rel ? `${rel}/${it.name}` : it.name;
28
+ if (it.isDirectory()) {
29
+ if (SKIP_DIRS.has(it.name))
30
+ continue;
31
+ out.push({ path: p, dir: true });
32
+ next.push(p);
33
+ }
34
+ else if (it.isFile()) {
35
+ if (SECRET_FILE.test(it.name) || it.name === '.DS_Store')
36
+ continue;
37
+ out.push({ path: p, dir: false });
38
+ }
39
+ }
40
+ }
41
+ level = next;
42
+ }
43
+ return out;
44
+ }
45
+ const subseq = (needle, hay) => { let i = 0; for (const c of hay) {
46
+ if (c === needle[i])
47
+ i++;
48
+ if (i === needle.length)
49
+ return true;
50
+ } return needle.length === 0; };
51
+ /** Best matches for what was typed after "@". Empty query = the top level. Lower score is better; ties go to the shorter path. Pure. */
52
+ export function searchFiles(entries, query, limit = 30) {
53
+ const q = query.toLowerCase().replace(/^\.\//, '');
54
+ if (!q)
55
+ return entries.filter(e => !e.path.includes('/')).sort((a, b) => Number(b.dir) - Number(a.dir) || a.path.localeCompare(b.path)).slice(0, limit);
56
+ const scored = [];
57
+ for (const e of entries) {
58
+ const p = e.path.toLowerCase(), base = p.slice(p.lastIndexOf('/') + 1);
59
+ const s = p === q ? 0 : p.startsWith(q) ? 1 : base.startsWith(q) ? 2 : base.includes(q) ? 3 : p.includes(q) ? 4 : subseq(q, p) ? 5 : -1;
60
+ if (s >= 0)
61
+ scored.push({ e, s });
62
+ }
63
+ return scored.sort((a, b) => a.s - b.s || a.e.path.length - b.e.path.length || a.e.path.localeCompare(b.e.path)).slice(0, limit).map(x => x.e);
64
+ }
65
+ //# sourceMappingURL=file-index.js.map
@@ -10,6 +10,8 @@ export interface GuiServer {
10
10
  url: string;
11
11
  close(): Promise<void>;
12
12
  }
13
+ /** Version in package.json right now. The page compares it with the version this process started with: after an update the files on disk are newer than the running server, and new screens would call routes it does not have. */
14
+ export declare function packageVersion(file?: string): string;
13
15
  export declare function openBrowser(url: string, platform?: NodeJS.Platform): void;
14
16
  /** The instruction that turns an owner's rough request into a brief the Director can act on. Pure. Exported for tests. */
15
17
  export declare function requestEnhancePrompt(draft: string, ctx: {
@@ -16,11 +16,24 @@ import { replayTeamRun, startTeamRun } from '../team/engine.js';
16
16
  import { detectClis } from '../team/cli-models.js';
17
17
  import { dispatchRunner } from '../team/runners.js';
18
18
  import { splitCliArgs } from '../team/cli-args.js';
19
+ import { handleFs } from './workspace-files.js';
20
+ import { listWorkspace, searchFiles } from './file-index.js';
19
21
  import { listTeamRuns, readTeamJournal } from '../team/journal.js';
20
22
  import { DEFAULT_MISSIONS, allAgentsOf, effectiveOrder } from '../team/types.js';
21
23
  import { mkdirSync, writeFileSync } from 'node:fs';
22
24
  import { dirname } from 'node:path';
23
25
  const GUI_DIR = resolve(fileURLToPath(new URL('../../../gui/', import.meta.url)));
26
+ /** Version in package.json right now. The page compares it with the version this process started with: after an update the files on disk are newer than the running server, and new screens would call routes it does not have. */
27
+ export function packageVersion(file = fileURLToPath(new URL('../../../package.json', import.meta.url))) {
28
+ try {
29
+ const v = JSON.parse(readFileSync(file, 'utf8')).version;
30
+ return typeof v === 'string' ? v : '';
31
+ }
32
+ catch {
33
+ return '';
34
+ }
35
+ }
36
+ const START_VERSION = packageVersion();
24
37
  const MIME = { '.html': 'text/html; charset=utf-8', '.css': 'text/css; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.json': 'application/json; charset=utf-8', '.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon' };
25
38
  const ARTIFACT_RE = /^(report\.md|transcript\.md|handoff-ba\.md|qc-report-\d{1,3}\.md)$/;
26
39
  const RUN_ID_RE = /^team-\d{8}-\d{6}-[0-9a-f]{4}$/;
@@ -147,6 +160,7 @@ export async function startGuiServer(opts) {
147
160
  }
148
161
  } };
149
162
  let checks = 0, enhancing = false;
163
+ let fileCache = null; // "@" mentions: names of the workspace, refreshed every few seconds
150
164
  async function api(req, res, url) {
151
165
  const m = req.method ?? 'GET', p = url.pathname;
152
166
  if (m === 'GET' && p === '/api/events') {
@@ -170,10 +184,12 @@ export async function startGuiServer(opts) {
170
184
  res.write('event: ready\ndata: {}\n\n');
171
185
  return;
172
186
  }
187
+ if (p.startsWith('/api/fs/'))
188
+ return handleFs(root, req, res, url);
173
189
  if (m === 'GET' && p === '/api/state') {
174
190
  const c = loadConfig();
175
191
  const configured = allAgents(c).some(a => a.cli !== 'auto' && a.cli !== 'simulated');
176
- return json(res, 200, { config: publicConfig(c), configExists: existsSync(teamConfigPath(root)), projectRoot: root, simulatedDefault: !configured,
192
+ return json(res, 200, { config: publicConfig(c), configExists: existsSync(teamConfigPath(root)), projectRoot: root, version: START_VERSION, diskVersion: packageVersion(), simulatedDefault: !configured,
177
193
  run: current ? { runId: current.handle.runId, goal: current.goal, simulated: current.simulated, startedAt: current.startedAt, running: current.outcome === null, outcome: current.outcome } : null });
178
194
  }
179
195
  if (m === 'PUT' && p === '/api/config') {
@@ -355,6 +371,12 @@ export async function startGuiServer(opts) {
355
371
  checks--;
356
372
  }
357
373
  }
374
+ if (m === 'GET' && p === '/api/files') {
375
+ const q = (url.searchParams.get('q') ?? '').slice(0, 200);
376
+ if (!fileCache || Date.now() - fileCache.at > 5000)
377
+ fileCache = { at: Date.now(), entries: listWorkspace(root) };
378
+ return json(res, 200, { files: searchFiles(fileCache.entries, q), total: fileCache.entries.length });
379
+ }
358
380
  if (m === 'GET' && p === '/api/clis')
359
381
  return json(res, 200, { clis: detectClis(), configFile: teamConfigPath(root) });
360
382
  if (m === 'POST' && p === '/api/runs/current/message') {
@@ -0,0 +1,35 @@
1
+ import { type Readable, type Writable } from 'node:stream';
2
+ /** Structural stand-ins for the http request/response (node:http is imported only by server.ts). */
3
+ type IncomingMessage = Readable & {
4
+ method?: string | undefined;
5
+ };
6
+ type ServerResponse = Writable & {
7
+ headersSent: boolean;
8
+ writeHead(status: number, headers?: Record<string, string | number>): unknown;
9
+ destroy(): unknown;
10
+ };
11
+ /** A single file or folder name that may be created or addressed. Returns an error sentence, or '' when fine. */
12
+ export declare function badName(name: string): string;
13
+ export interface FsEntry {
14
+ name: string;
15
+ dir: boolean;
16
+ size: number;
17
+ mtime: number;
18
+ }
19
+ export declare function listFolder(root: string, rel: unknown): {
20
+ path: string;
21
+ entries: FsEntry[];
22
+ sig: string;
23
+ truncated: boolean;
24
+ };
25
+ /** What a file is served as. Anything that could run in a browser (html, svg, scripts) is plain text. */
26
+ export declare function fileKind(name: string): {
27
+ mime: string;
28
+ inline: boolean;
29
+ cap: number;
30
+ };
31
+ /** Put the finished upload at `dest` without ever replacing a file. Hard link first; drives that have no hard links (exFAT, FAT, some network shares) get an exclusive copy. */
32
+ export declare function placeNew(tmp: string, dest: string, link?: (a: string, b: string) => void): void;
33
+ /** Handles every /api/fs/* request (token already checked by the caller). Always responds. */
34
+ export declare function handleFs(rootIn: string, req: IncomingMessage, res: ServerResponse, url: URL): Promise<void>;
35
+ export {};
@@ -0,0 +1,278 @@
1
+ // Workspace file explorer API (/api/fs/*): list, read, upload, mkdir, rename/move, move-to-trash. Everything is confined to the workspace root.
2
+ import { constants as fsConstants, copyFileSync, createReadStream, createWriteStream, existsSync, linkSync, lstatSync, mkdirSync, readdirSync, realpathSync, renameSync, rmSync, statSync } from 'node:fs';
3
+ import { pipeline } from 'node:stream/promises';
4
+ import { Transform } from 'node:stream';
5
+ import { createHash, randomBytes } from 'node:crypto';
6
+ import { dirname, extname, join, sep } from 'node:path';
7
+ /** Same secret-looking rule as the "@" mention index (file-index.ts). */
8
+ const SECRET_FILE = /^\.env(\..*)?$|\.(pem|key|p12|pfx)$|^id_(rsa|ed25519|ecdsa)$/i;
9
+ const HIDDEN_NAMES = new Set(['.git', '.ckit', '.DS_Store']);
10
+ const MAX_UPLOAD_BYTES = 2 * 1024 ** 3, MAX_TEXT_PREVIEW = 2 * 1024 ** 2, MAX_IMAGE_PREVIEW = 30 * 1024 ** 2, MAX_ENTRIES = 5000;
11
+ const CTRL = /[\u0000-\u001f\u007f]/;
12
+ class FsError extends Error {
13
+ status;
14
+ constructor(status, message) {
15
+ super(message);
16
+ this.status = status;
17
+ }
18
+ }
19
+ const bad = (m, status = 400) => { throw new FsError(status, m); };
20
+ const TEXT_EXT = new Set(['.txt', '.md', '.markdown', '.json', '.jsonl', '.yml', '.yaml', '.toml', '.ini', '.cfg', '.conf', '.csv', '.tsv', '.log', '.xml', '.html', '.htm', '.svg', '.css', '.scss', '.less', '.js', '.mjs', '.cjs', '.jsx', '.ts', '.tsx', '.py', '.rb', '.go', '.rs', '.java', '.kt', '.c', '.h', '.cpp', '.hpp', '.cs', '.php', '.sh', '.zsh', '.bat', '.sql', '.vue', '.svelte', '.drawio', '.gitignore', '.editorconfig', '.lock']);
21
+ const IMAGE_MIME = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp' };
22
+ const NAMELESS_TEXT = new Set(['readme', 'license', 'makefile', 'dockerfile', 'changelog']);
23
+ /** A single file or folder name that may be created or addressed. Returns an error sentence, or '' when fine. */
24
+ export function badName(name) {
25
+ if (!name || name === '.' || name === '..')
26
+ return 'Type a file or folder name.';
27
+ if (name.length > 200)
28
+ return 'That name is too long; use fewer than 200 characters.';
29
+ if (/[\\/]/.test(name) || CTRL.test(name))
30
+ return 'Names cannot contain slashes or hidden control characters; remove them and try again.';
31
+ if (HIDDEN_NAMES.has(name) || SECRET_FILE.test(name))
32
+ return 'CKit keeps that name private (version-control, CKit internals and key/secret files); choose another name.';
33
+ return '';
34
+ }
35
+ /** Relative path (POSIX, no leading slash) -> segments, or throws. Empty path = workspace root. */
36
+ function segmentsOf(rel) {
37
+ if (typeof rel !== 'string')
38
+ return bad('A path is required.');
39
+ if (rel.includes('\0') || CTRL.test(rel))
40
+ return bad('That path has unreadable characters; pick the item from the list instead.');
41
+ if (/^([/\\]|[A-Za-z]:)/.test(rel) || rel.includes('\\'))
42
+ return bad('Use a path inside the workspace folder, like "docs/notes.md".');
43
+ const segs = rel.split('/').filter(s => s !== '' && s !== '.');
44
+ for (const s of segs) {
45
+ if (s === '..')
46
+ bad('Paths cannot leave the workspace folder.', 403);
47
+ const why = badName(s);
48
+ if (why)
49
+ bad(why, 403);
50
+ }
51
+ return segs;
52
+ }
53
+ /** Resolve inside root. No existing component may be a symlink (nothing is followed); the nearest existing parent must still live under root. */
54
+ function resolveIn(root, relRaw) {
55
+ const segs = segmentsOf(relRaw);
56
+ let cur = root, exists = true;
57
+ for (const s of segs) {
58
+ const next = join(cur, s);
59
+ let st;
60
+ try {
61
+ st = lstatSync(next);
62
+ }
63
+ catch {
64
+ exists = false;
65
+ cur = next;
66
+ continue;
67
+ }
68
+ if (!exists)
69
+ continue;
70
+ if (st.isSymbolicLink())
71
+ bad('That item is a shortcut (symbolic link) and is not opened here, for safety.', 403);
72
+ cur = next;
73
+ }
74
+ let near = cur;
75
+ while (!existsSync(near) && near !== root && near !== dirname(near))
76
+ near = dirname(near);
77
+ const real = realpathSync(near);
78
+ if (real !== root && !real.startsWith(root + sep))
79
+ bad('Paths cannot leave the workspace folder.', 403);
80
+ return { abs: cur, rel: segs.join('/'), segs, exists };
81
+ }
82
+ const needExisting = (r) => (r.exists ? r : bad('That file or folder is not there any more; refresh the list.', 404));
83
+ export function listFolder(root, rel) {
84
+ const r = needExisting(resolveIn(root, rel));
85
+ if (!statSync(r.abs).isDirectory())
86
+ bad('That is a file, not a folder.');
87
+ const entries = [];
88
+ let truncated = false;
89
+ for (const it of readdirSync(r.abs, { withFileTypes: true })) {
90
+ if (it.isSymbolicLink() || (!it.isDirectory() && !it.isFile()) || badName(it.name) || CTRL.test(it.name))
91
+ continue;
92
+ if (entries.length >= MAX_ENTRIES) {
93
+ truncated = true;
94
+ break;
95
+ }
96
+ try {
97
+ const st = statSync(join(r.abs, it.name));
98
+ entries.push({ name: it.name, dir: it.isDirectory(), size: it.isDirectory() ? 0 : st.size, mtime: Math.round(st.mtimeMs) });
99
+ }
100
+ catch { /* vanished */ }
101
+ }
102
+ entries.sort((a, b) => Number(b.dir) - Number(a.dir) || a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: 'base' }));
103
+ const sig = createHash('sha1').update(entries.map(e => `${e.name}|${e.dir ? 'd' : e.size}|${e.mtime}`).join('\n')).digest('hex').slice(0, 16);
104
+ return { path: r.rel, entries, sig, truncated };
105
+ }
106
+ /** What a file is served as. Anything that could run in a browser (html, svg, scripts) is plain text. */
107
+ export function fileKind(name) {
108
+ const ext = extname(name).toLowerCase();
109
+ if (IMAGE_MIME[ext])
110
+ return { mime: IMAGE_MIME[ext], inline: true, cap: MAX_IMAGE_PREVIEW };
111
+ if (ext === '.pdf')
112
+ return { mime: 'application/pdf', inline: true, cap: MAX_IMAGE_PREVIEW };
113
+ if (TEXT_EXT.has(ext) || (ext === '' && (NAMELESS_TEXT.has(name.toLowerCase()) || name.startsWith('.'))))
114
+ return { mime: 'text/plain; charset=utf-8', inline: true, cap: MAX_TEXT_PREVIEW };
115
+ return { mime: 'application/octet-stream', inline: false, cap: 0 };
116
+ }
117
+ const jsonOut = (res, status, body) => {
118
+ const s = JSON.stringify(body);
119
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', 'content-length': Buffer.byteLength(s) });
120
+ res.end(s);
121
+ };
122
+ async function jsonBody(req) {
123
+ const chunks = [];
124
+ let n = 0;
125
+ for await (const c of req) {
126
+ n += c.length;
127
+ if (n > 100_000)
128
+ bad('Request too large.', 413);
129
+ chunks.push(c);
130
+ }
131
+ const t = Buffer.concat(chunks).toString('utf8');
132
+ let v;
133
+ try {
134
+ v = t ? JSON.parse(t) : {};
135
+ }
136
+ catch {
137
+ return bad('Invalid request.');
138
+ }
139
+ return v !== null && typeof v === 'object' && !Array.isArray(v) ? v : {};
140
+ }
141
+ const stamp = () => new Date().toISOString().replace(/[:.]/g, '-');
142
+ function uniqueName(dirAbs, name) {
143
+ if (!existsSync(join(dirAbs, name)))
144
+ return name;
145
+ const dot = name.lastIndexOf('.'), base = dot > 0 ? name.slice(0, dot) : name, ext = dot > 0 ? name.slice(dot) : '';
146
+ for (let i = 1; i < 10_000; i++) {
147
+ const c = `${base} (${i})${ext}`;
148
+ if (!existsSync(join(dirAbs, c)))
149
+ return c;
150
+ }
151
+ return bad('Too many files with that name; rename the file first.', 409);
152
+ }
153
+ /** Put the finished upload at `dest` without ever replacing a file. Hard link first; drives that have no hard links (exFAT, FAT, some network shares) get an exclusive copy. */
154
+ export function placeNew(tmp, dest, link = linkSync) {
155
+ try {
156
+ link(tmp, dest);
157
+ }
158
+ catch (e) {
159
+ if (e.code === 'EEXIST')
160
+ throw e;
161
+ copyFileSync(tmp, dest, fsConstants.COPYFILE_EXCL);
162
+ }
163
+ }
164
+ /** Handles every /api/fs/* request (token already checked by the caller). Always responds. */
165
+ export async function handleFs(rootIn, req, res, url) {
166
+ const m = req.method ?? 'GET', p = url.pathname, root = realpathSync(rootIn);
167
+ try {
168
+ if (m === 'GET' && p === '/api/fs/list')
169
+ return jsonOut(res, 200, listFolder(root, url.searchParams.get('path') ?? ''));
170
+ if (m === 'GET' && p === '/api/fs/file') {
171
+ const r = needExisting(resolveIn(root, url.searchParams.get('path')));
172
+ if (!r.rel)
173
+ bad('Pick a file.');
174
+ const st = statSync(r.abs);
175
+ if (!st.isFile())
176
+ bad('That is a folder; open it instead.');
177
+ const name = r.segs[r.segs.length - 1], kind = fileKind(name), download = url.searchParams.get('download') === '1';
178
+ if (!download && (!kind.inline || st.size > kind.cap))
179
+ bad(kind.inline ? 'This file is too large to preview; use Download.' : 'No preview for this type of file; use Download.', 413);
180
+ const headers = { 'content-type': download ? 'application/octet-stream' : kind.mime, 'content-length': st.size, 'cache-control': 'no-store', 'x-content-type-options': 'nosniff',
181
+ 'content-disposition': `${download ? 'attachment' : 'inline'}; filename*=UTF-8''${encodeURIComponent(name)}` };
182
+ if (!download && kind.mime !== 'application/pdf')
183
+ headers['content-security-policy'] = "default-src 'none'; style-src 'unsafe-inline'; sandbox";
184
+ res.writeHead(200, headers);
185
+ await pipeline(createReadStream(r.abs), res);
186
+ return;
187
+ }
188
+ if (m === 'POST' && p === '/api/fs/mkdir') {
189
+ const r = resolveIn(root, (await jsonBody(req))['path']);
190
+ if (!r.rel)
191
+ bad('Type a folder name.');
192
+ if (r.exists)
193
+ bad('A file or folder with that name already exists; choose another name.', 409);
194
+ mkdirSync(r.abs, { recursive: true });
195
+ return jsonOut(res, 200, { ok: true, path: r.rel });
196
+ }
197
+ if (m === 'POST' && p === '/api/fs/upload') {
198
+ const dir = needExisting(resolveIn(root, url.searchParams.get('path') ?? ''));
199
+ if (!statSync(dir.abs).isDirectory())
200
+ bad('Upload into a folder, not a file.');
201
+ const name = url.searchParams.get('name') ?? '', why = badName(name);
202
+ if (why)
203
+ bad(why);
204
+ const tmpDir = join(root, '.ckit', 'tmp');
205
+ mkdirSync(tmpDir, { recursive: true });
206
+ const tmp = join(tmpDir, `up-${randomBytes(8).toString('hex')}`);
207
+ let size = 0;
208
+ const meter = new Transform({ transform(chunk, _e, cb) { size += chunk.length; cb(size > MAX_UPLOAD_BYTES ? new Error('too large') : null, chunk); } });
209
+ try {
210
+ await pipeline(req, meter, createWriteStream(tmp, { flags: 'wx', mode: 0o644 }));
211
+ }
212
+ catch {
213
+ rmSync(tmp, { force: true });
214
+ return jsonOut(res, size > MAX_UPLOAD_BYTES ? 413 : 400, { error: size > MAX_UPLOAD_BYTES ? 'That file is larger than 2 GB.' : 'The upload was interrupted; try again.' });
215
+ }
216
+ let final = '';
217
+ try {
218
+ for (let i = 0; i < 20 && !final; i++) {
219
+ const c = uniqueName(dir.abs, name);
220
+ try {
221
+ placeNew(tmp, join(dir.abs, c));
222
+ final = c;
223
+ }
224
+ catch (e) {
225
+ if (e.code !== 'EEXIST')
226
+ throw e;
227
+ }
228
+ }
229
+ }
230
+ finally {
231
+ rmSync(tmp, { force: true });
232
+ }
233
+ if (!final)
234
+ bad('Could not pick a free file name; try again.', 409);
235
+ return jsonOut(res, 200, { ok: true, name: final, renamed: final !== name, path: dir.rel ? `${dir.rel}/${final}` : final, size });
236
+ }
237
+ if (m === 'POST' && p === '/api/fs/rename') {
238
+ const b = await jsonBody(req), from = needExisting(resolveIn(root, b['from'])), to = resolveIn(root, b['to']);
239
+ if (!from.rel || !to.rel)
240
+ bad('The workspace folder itself cannot be renamed or moved.', 403);
241
+ if (to.exists)
242
+ bad('Something with that name is already there; choose another name.', 409);
243
+ if (to.rel === from.rel || to.rel.startsWith(from.rel + '/'))
244
+ bad('A folder cannot be moved into itself.');
245
+ const parent = resolveIn(root, to.segs.slice(0, -1).join('/'));
246
+ if (!parent.exists || !statSync(parent.abs).isDirectory())
247
+ bad('The destination folder does not exist.', 404);
248
+ renameSync(from.abs, to.abs);
249
+ return jsonOut(res, 200, { ok: true, path: to.rel });
250
+ }
251
+ if (m === 'POST' && p === '/api/fs/delete') {
252
+ const r = needExisting(resolveIn(root, (await jsonBody(req))['path']));
253
+ if (!r.rel)
254
+ bad('The workspace folder itself cannot be deleted.', 403);
255
+ const dest = join(root, '.ckit', 'trash', `${stamp()}-${randomBytes(2).toString('hex')}`, ...r.segs);
256
+ mkdirSync(dirname(dest), { recursive: true });
257
+ renameSync(r.abs, dest);
258
+ return jsonOut(res, 200, { ok: true, trashedTo: dest.slice(root.length + 1).split(sep).join('/') });
259
+ }
260
+ return jsonOut(res, 404, { error: 'Unknown request.' });
261
+ }
262
+ catch (e) {
263
+ if (e instanceof FsError) {
264
+ if (!res.headersSent)
265
+ jsonOut(res, e.status, { error: e.message });
266
+ else
267
+ res.destroy();
268
+ return;
269
+ }
270
+ if (res.headersSent) {
271
+ res.destroy();
272
+ return;
273
+ }
274
+ const code = e.code;
275
+ jsonOut(res, code === 'ENOENT' ? 404 : 500, { error: code === 'ENOENT' ? 'That file or folder is not there any more; refresh the list.' : 'The file system refused that action; check the folder permissions and try again.' });
276
+ }
277
+ }
278
+ //# sourceMappingURL=workspace-files.js.map
@@ -317,6 +317,8 @@ export function startTeamRun(opts) {
317
317
  };
318
318
  const ruleBrief = () => `Brief: deliver "${oneLine(goal, 300)}".${atts.length ? ` The owner attached ${atts.length} file(s): ${atts.map(a => a.name).join(', ')}. Every team reads them as part of the request.` : ''} Pipeline: ${roster().map(t => t.name).join(' -> ') || 'Director only'} -> final report to the owner.${roster().map(t => `\n\n### TEAM ${t.id}\nDo: ${t.mission} (for "${oneLine(goal, 200)}")\nDeliverable: your report on your part of the goal.\nOut of scope: anything another team owns.`).join('')}`;
319
319
  const qaRounds = [];
320
+ const MAX_OWNER_ASKS = 3; // mid-run questions the Director may pass on to the owner, per run
321
+ let ownerAsks = 0;
320
322
  let needRounds = 0, forced = false, waiting = null;
321
323
  const waitForOwner = (assume) => new Promise(res => { waiting = { assumptions: assume, wake: r => { waiting = null; res(r); } }; });
322
324
  /** One Director triage turn; the text always ends up parsed by parseDirectorDecision. Simulated / rule-based directors answer from the goal flags. */
@@ -480,10 +482,26 @@ export function startTeamRun(opts) {
480
482
  if (pid === 'director') {
481
483
  let ans = `Re "${oneLine(question, 200)}": everything I know is in the brief for your team:\n${briefOf(asker.team)}`;
482
484
  if (modelDirector()) {
483
- const t = await directorAsk(`answer ${teamName(asker.team)}`, `${role(config.director, 'A team asks you a question about its brief. Answer in one short message; do not restate the whole brief.')}\nTEAM ROSTER (flow order):\n${rosterText()}\n${common()}\nYOUR EARLIER BRIEF FOR THAT TEAM:\n${briefOf(asker.team)}\nQUESTION from ${asker.name} (${teamName(asker.team)}): ${question}`);
485
+ const t = await directorAsk(`answer ${teamName(asker.team)}`, `${role(config.director, `A team asks you a question about its brief. Answer in one short message; do not restate the whole brief.${ownerAsks < MAX_OWNER_ASKS ? ' If the answer is a decision only the owner can make (scope, acceptance, trade-off or missing input that the goal, your brief and the owner notes do not settle) and a wrong guess would waste real work, do not guess: reply with ONLY a line "ASK OWNER: <one clear question in the owner\'s language>" and, when sensible, a line "ASSUMPTION IF NO ANSWER: <what you would assume>". Otherwise answer it yourself.' : ''}`)}\nTEAM ROSTER (flow order):\n${rosterText()}\n${common()}\nYOUR EARLIER BRIEF FOR THAT TEAM:\n${briefOf(asker.team)}\nQUESTION from ${asker.name} (${teamName(asker.team)}): ${question}`);
484
486
  if (t?.trim())
485
487
  ans = t;
486
488
  }
489
+ else if (/\[sim-ask-owner\]/i.test(goal) && ownerAsks === 0)
490
+ ans = 'ASK OWNER: Should empty input fail loudly or be ignored?\nASSUMPTION IF NO ANSWER: Empty input fails with a clear error.';
491
+ const esc = /^[\s>*_\-#]*ASK OWNER\**\s*:\**\s*(.+)$/im.exec(ans);
492
+ if (esc && ownerAsks < MAX_OWNER_ASKS) {
493
+ ownerAsks++;
494
+ const q = oneLine(esc[1], 600), assume = (/^[\s>*_\-#]*ASSUMPTIONS? IF NO ANSWER\**\s*:\**\s*(.+)$/im.exec(ans)?.[1] ?? '').trim();
495
+ directorSay('all', `${teamName(asker.team)} asked something only you can decide:\n${q}${assume ? `\n\nASSUMPTIONS IF NO ANSWER:\n${assume}` : ''}`);
496
+ emit({ type: 'run.waiting', round: ownerAsks, questions: q, assumptions: assume || null, team: asker.team });
497
+ const w = await waitForOwner(assume);
498
+ halted();
499
+ const decided = w.how === 'proceed' ? assume : w.text;
500
+ notes.push(`Owner's decision on "${oneLine(q, 200)}": ${decided}`);
501
+ ans = `Re "${oneLine(question, 200)}": ${w.how === 'proceed' ? 'the owner chose to proceed with this assumption' : 'the owner decided'}: ${decided}`;
502
+ }
503
+ else if (esc)
504
+ ans = `Re "${oneLine(question, 200)}": no further owner decision is available; use your best judgement, state the assumption you make in your handoff under OPEN.`;
487
505
  return directorSay(asker.id, ans);
488
506
  }
489
507
  const lead = agentsOf(pid)[0];
@@ -194,12 +194,13 @@ export type TeamEvent = {
194
194
  readonly summary: string;
195
195
  readonly checklist?: string;
196
196
  }
197
- /** Director triage at intake asked the owner for more information; nothing runs until the owner answers (or presses proceed / stop). */
197
+ /** The Director asked the owner: at intake (no team has started) or mid-run for a team question only the owner can decide (`team` set). Nothing runs until the owner answers (or presses proceed / stop). */
198
198
  | {
199
199
  readonly type: 'run.waiting';
200
200
  readonly round: number;
201
201
  readonly questions: string;
202
- readonly assumptions: string | null;
202
+ readonly assumptions: string | null; /** set when the question came up mid-run: the team whose question the Director passed on to the owner */
203
+ readonly team?: string;
203
204
  } | {
204
205
  readonly type: 'user.message';
205
206
  readonly text: string;
package/gui/app.css CHANGED
@@ -181,7 +181,7 @@ a.att:hover{border-color:var(--cy)}
181
181
  #lanename{font:700 10px var(--mono);letter-spacing:.08em;color:var(--vi);border:1px solid #4a3a7a;border-radius:3px;padding:4px 8px;white-space:nowrap;text-transform:uppercase}#lanename[hidden]{display:none}
182
182
  #now.ask{background:#ffd9a0;border-color:#5a2d00}#now.ask .nowtag{background:#5a2d00;color:#ffd9a0}
183
183
  .qcard{border:1px solid var(--am);background:rgba(243,165,68,.07);border-radius:6px;padding:10px 14px;font-size:13px;line-height:1.5}.qcard b{color:var(--am)}.qcard ol,.qcard ul{margin:6px 0 6px 20px;padding:0}.qcard li{margin:3px 0}.qcard .qhint{font:11px var(--mono);color:var(--mu);margin-top:6px}
184
- #wbtns{margin:4px 0}#wbtns[hidden],#lanewrap[hidden]{display:none}#lanewrap{display:block;margin:0 0 6px}#lanewrap select,.laneSel{font:11px var(--mono);width:100%}
184
+ #composer.wait{border-color:var(--am);box-shadow:0 0 0 1px var(--am),0 0 26px rgba(243,165,68,.35);animation:waitpulse 1.6s ease-in-out infinite}#composer.wait #clabel{color:var(--am)}@keyframes waitpulse{50%{box-shadow:0 0 0 1px var(--am),0 0 10px rgba(243,165,68,.15)}}@media (prefers-reduced-motion:reduce){#composer.wait{animation:none}}.qcard .qgo{margin-top:8px}#wbtns{margin:4px 0}#wbtns[hidden],#lanewrap[hidden]{display:none}#lanewrap{display:block;margin:0 0 6px}#lanewrap select,.laneSel{font:11px var(--mono);width:100%}
185
185
  .rnd{font:700 9px var(--mono);letter-spacing:.08em;color:var(--mu);border:1px solid var(--b1);border-radius:8px;padding:1px 6px;margin-left:6px;text-transform:uppercase}
186
186
  .rteam.dim,.tile.dim{opacity:.35}
187
187
  .card.ho.click{cursor:pointer}.card.ho .hos{font-size:11px;line-height:1.4;margin-top:3px;color:#c4d0e4}.card.ho .hos b{display:block;font:700 9px var(--mono);letter-spacing:.1em;color:var(--cy)}
@@ -197,7 +197,7 @@ table.runs td.warn{color:var(--am)}
197
197
  .chkrow{display:flex;gap:8px;align-items:flex-start;margin:6px 0}.chkrow input{width:auto;margin-top:3px}
198
198
 
199
199
  /* text dialog (askText) */
200
- .ask{position:fixed;inset:0;z-index:80;display:grid;place-items:center;background:rgba(3,5,10,.72);backdrop-filter:blur(6px);animation:askfade .14s ease-out}
200
+ .asklayer{position:fixed;inset:0;z-index:80;display:grid;place-items:center;background:rgba(3,5,10,.72);backdrop-filter:blur(6px);animation:askfade .14s ease-out}
201
201
  .askcard{width:min(520px,92vw);background:linear-gradient(180deg,rgba(33,214,232,.07),transparent 90px),var(--p1);border:1px solid var(--b2);border-top:2px solid var(--cy);border-radius:6px;box-shadow:0 24px 80px rgba(0,0,0,.6),0 0 60px rgba(33,214,232,.14);animation:askpop .18s cubic-bezier(.2,1.2,.4,1)}
202
202
  .askcard header{display:flex;justify-content:space-between;align-items:center;padding:14px 18px 4px}.askcard header b{font:700 13px var(--mono);letter-spacing:.14em;text-transform:uppercase;color:#fff}
203
203
  .askx{border:0;background:none;color:var(--mu);padding:2px 6px;font-size:13px}.askx:hover{color:#fff;box-shadow:none}
@@ -214,3 +214,57 @@ table.runs td.warn{color:var(--am)}
214
214
  .enhta{width:100%;height:52vh;resize:vertical;font-size:13.5px;line-height:1.55;border-color:#4a3a86}.enhnote{margin:10px 0 0;font-size:12px;color:var(--mu)}
215
215
  @media (max-width:820px){.enhcols{grid-template-columns:1fr}.enhta{height:34vh}.enhorig{max-height:18vh}}
216
216
  #comicpanels:empty::before{content:'Comic view retells a run as comic panels: who said what, each handoff, each verdict.\A Nothing to show yet: start a mission in the box below, or open Runs and replay an old one.';white-space:pre-line;display:block;margin:12vh auto 0;max-width:560px;text-align:center;font:13px/1.7 var(--mono);color:var(--mu)}
217
+ /* "@" file mentions */
218
+ .ment{position:fixed;z-index:90;display:flex;flex-direction:column;overflow:auto;background:var(--p1);border:1px solid var(--b2);border-top:2px solid var(--cy);border-radius:6px;box-shadow:0 18px 60px rgba(0,0,0,.65),0 0 40px rgba(33,214,232,.12);padding:4px}
219
+ .menth{display:flex;justify-content:space-between;gap:12px;padding:6px 8px 7px;font:600 10px var(--mono);letter-spacing:.08em;color:var(--mu);position:sticky;top:-4px;background:var(--p1);white-space:nowrap}.menth span:first-child{overflow:hidden;text-overflow:ellipsis}.menth span:last-child{letter-spacing:0;font-weight:400}
220
+ .mentrow{display:flex;align-items:baseline;gap:8px;padding:6px 8px;border-radius:4px;cursor:pointer;font:13px var(--mono);white-space:nowrap}.mentrow b{font-weight:600;color:#e6eefb}.mentrow small{color:var(--mu);font-size:11px;overflow:hidden;text-overflow:ellipsis;min-width:0}
221
+ .menti{width:10px;color:var(--cy);flex:none}.mentrow:hover{background:rgba(255,255,255,.04)}.mentrow.on{background:rgba(33,214,232,.13);box-shadow:inset 2px 0 0 var(--cy)}.mentnone{padding:10px 8px;font-size:12px;color:var(--mu)}
222
+ /* workspace explorer */
223
+ #ws{cursor:pointer;border-radius:4px;transition:.15s}#ws:hover{background:rgba(33,214,232,.08)}#ws:focus-visible{outline:1px solid var(--cy)}
224
+ .dlg.exdlg{width:min(1240px,96vw);height:min(84vh,860px);max-height:none}
225
+ .exdlg header{gap:12px}.exdlg header b{font:700 13px var(--mono);letter-spacing:.14em;color:#fff;white-space:nowrap}
226
+ .exroot{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--mu);font-size:11px;direction:rtl;text-align:left}
227
+ .excopy{font-size:11px;padding:3px 9px}.exlive{display:flex;align-items:center;gap:5px;font:600 10px var(--mono);letter-spacing:.1em;text-transform:uppercase;color:var(--gr)}
228
+ .exlive i{width:7px;height:7px;border-radius:50%;background:var(--gr);box-shadow:0 0 8px var(--gr);animation:blink 2s infinite}.exlive.off{color:var(--rd)}.exlive.off i{background:var(--rd);box-shadow:none;animation:none}
229
+ .extool{display:flex;align-items:center;gap:8px;padding:10px 16px;border-bottom:1px solid var(--b1);flex:none}
230
+ .extool button{white-space:nowrap}.exup{width:32px;padding:6px 0;font-weight:700}
231
+ .exbc{flex:1;min-width:0;display:flex;align-items:center;gap:2px;overflow:hidden;white-space:nowrap}
232
+ .excrumb{background:none;border:1px solid transparent;padding:4px 8px;color:var(--mu);max-width:200px;overflow:hidden;text-overflow:ellipsis;flex:0 1 auto;min-width:0}
233
+ .excrumb:hover{color:#fff;border-color:var(--b2);box-shadow:none}.excrumb.cur{color:var(--cy);font-weight:600}.excrumb.dropto{border-color:var(--cy);background:rgba(33,214,232,.16);color:#fff}.exsep{color:var(--b2)}
234
+ .exfilter{width:190px;flex:none;padding:6px 9px}.exref{border-color:var(--vi);color:#d8c2ff;background:rgba(163,107,255,.1)}
235
+ .exmain{flex:1;min-height:0;display:grid;grid-template-columns:minmax(0,1fr) 0}.exdlg.hasprev .exmain{grid-template-columns:minmax(0,1fr) minmax(300px,38%)}
236
+ .exlist{position:relative;display:flex;flex-direction:column;min-width:0;min-height:0}.exprev{min-width:0;overflow:hidden;display:flex;flex-direction:column;border-left:1px solid var(--b1);background:#080d17}
237
+ .exdlg:not(.hasprev) .exprev{display:none}
238
+ .exrow{display:grid;grid-template-columns:34px minmax(0,1fr) 84px 108px 118px;align-items:center;gap:6px;padding:0 16px;height:36px;flex:none}
239
+ .exhead{height:30px;border-bottom:1px solid var(--b1);background:#09101c}.exhead>span:first-child{display:block}
240
+ .exsort{background:none;border:0;padding:0;text-align:left;font:600 10px var(--mono);letter-spacing:.1em;text-transform:uppercase;color:var(--mu);height:100%}.exsort:hover{color:#fff;box-shadow:none}.exsort.on{color:var(--cy)}.exsort.on::after{content:' ' attr(data-arrow);font-size:8px}
241
+ .exrows{flex:1;min-height:0;overflow:auto;outline:none;scrollbar-gutter:stable}
242
+ .exitem{border-bottom:1px solid rgba(37,51,71,.45);cursor:default;user-select:none;position:relative;border-left:2px solid transparent;padding-left:14px}
243
+ .exitem:hover{background:rgba(33,214,232,.05)}.exitem.sel{background:rgba(33,214,232,.14);border-left-color:var(--cy)}.exrows:focus-within .exitem.sel{background:rgba(33,214,232,.2)}
244
+ .exitem.dropto{background:rgba(163,107,255,.25);outline:1px dashed var(--vi);outline-offset:-2px}
245
+ .exitem.pulse{animation:expulse 2.4s ease-out}@keyframes expulse{0%{background:rgba(74,214,154,.4)}100%{background:transparent}}
246
+ .exic{font:700 11px var(--mono);text-align:center;width:26px;height:22px;line-height:22px;border-radius:4px;background:#121b2b;color:var(--mu)}
247
+ .exic.dir{color:var(--am);background:rgba(243,165,68,.12);font-size:13px}.exic.img{color:var(--mg);background:rgba(240,79,155,.12)}.exic.doc{color:var(--bl);background:rgba(79,140,255,.12)}.exic.code{color:var(--cy);background:rgba(33,214,232,.1);font-size:9px}
248
+ .exname{display:flex;align-items:center;gap:8px;min-width:0}.exn{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}
249
+ .exbadge{flex:none;font:700 9px var(--mono);letter-spacing:.08em;padding:1px 6px;border-radius:9px;border:1px solid}
250
+ .exbadge.new{color:var(--gr);border-color:#1f5b44;background:rgba(74,214,154,.12)}.exbadge.chg{color:var(--am);border-color:#6b4a1c;background:rgba(243,165,68,.1)}.exbadge.run{color:var(--vi);border-color:#4b3380;background:rgba(163,107,255,.1)}
251
+ .exsize,.exmod{color:var(--mu);font-size:12px;white-space:nowrap;font-variant-numeric:tabular-nums}
252
+ .exacts{display:flex;gap:2px;justify-content:flex-end;opacity:0;transition:opacity .12s}.exitem:hover .exacts,.exitem.sel .exacts{opacity:1}
253
+ .exact{padding:2px 6px;font-size:12px;line-height:18px;border-color:transparent;background:none;color:var(--mu)}.exact:hover{color:#fff;border-color:var(--b2);box-shadow:none}
254
+ .exempty,.exnoprev{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:8px;text-align:center;color:var(--mu);padding:30px;flex:1}
255
+ .exebig{font:700 34px var(--mono);color:var(--b2)}.exetitle{font-size:14px;color:var(--tx);font-weight:600}.exetitle.err{color:var(--rd)}.exesub{font-size:12px;max-width:380px;line-height:1.5}
256
+ .exdrop{display:none;position:absolute;inset:0;z-index:3;place-items:center;font:700 15px var(--mono);color:#fff;background:rgba(33,214,232,.12);border:2px dashed var(--cy);pointer-events:none}.exlist.over .exdrop{display:grid}
257
+ .exph{display:flex;align-items:center;justify-content:space-between;gap:8px;padding:12px 14px 2px}.exphn{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:13px;color:#fff}
258
+ .exmeta{display:flex;gap:12px;padding:0 14px;color:var(--mu);font-size:11px}.exbtns{display:flex;gap:8px;padding:10px 14px;flex-wrap:wrap}
259
+ .exbtns .btn,.exnoprev .btn{display:inline-block;font:inherit;color:var(--tx);background:var(--p2);border:1px solid var(--b2);border-radius:4px;padding:6px 12px;text-decoration:none}.exbtns .btn:hover,.exnoprev .btn:hover{border-color:var(--cy)}.exnoprev .btn.primary{background:linear-gradient(135deg,#1b6dd8,#7a3fd0);border-color:#6f8cff}
260
+ .exbody{flex:1;min-height:0;overflow:auto;border-top:1px solid var(--b1);display:flex;flex-direction:column}.extext{margin:0;padding:12px 14px;font:12px/1.55 var(--mono);color:#cfe0f3;white-space:pre-wrap;word-break:break-word;tab-size:2}
261
+ .eximg{max-width:100%;margin:12px auto;display:block;background:repeating-conic-gradient(#111a2a 0 25%,#0b1220 0 50%) 0 0/16px 16px;border:1px solid var(--b1);object-fit:contain}.exload{padding:20px;color:var(--mu)}
262
+ .exups{max-height:116px;overflow:auto;border-top:1px solid var(--b1);padding:6px 16px;flex:none}
263
+ .exu{display:grid;grid-template-columns:minmax(0,1fr) 130px minmax(0,1.2fr) 22px;gap:10px;align-items:center;font-size:12px;height:24px}.exun{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
264
+ .exubar{height:5px;border-radius:3px;background:#121b2b;overflow:hidden}.exubar i{display:block;height:100%;background:linear-gradient(90deg,var(--cy),var(--vi));transition:width .15s}
265
+ .exu.ok .exubar i{background:var(--gr)}.exu.bad .exubar i{background:var(--rd)}.exust{color:var(--mu);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.exu.bad .exust{color:var(--rd)}.exu.ok .exust{color:var(--gr)}
266
+ .exfoot{justify-content:space-between!important;align-items:center;font-size:11px;color:var(--mu)}.exstat.err{color:var(--rd)}.exhint{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}
267
+ @media (max-width:1000px){.exdlg.hasprev .exmain{grid-template-columns:minmax(0,1fr);grid-template-rows:minmax(0,1fr) 40%}.exdlg.hasprev .exprev{border-left:0;border-top:1px solid var(--b1)}.exfilter{width:130px}}
268
+
269
+ .stale{position:fixed;left:50%;bottom:14px;transform:translateX(-50%);z-index:60;max-width:min(760px,92vw);padding:9px 14px;border:1px solid var(--am);border-radius:8px;background:#1a1407;color:var(--am);font-size:12.5px;line-height:1.45;box-shadow:0 8px 30px rgba(0,0,0,.5)}
270
+ .exupl{max-width:230px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
package/gui/app.js CHANGED
@@ -33,6 +33,7 @@
33
33
  started: 0, ended: 0, outcome: null, replay: false, history: true, buckets: [], tokBuckets: [], handoffs: [], flowBacks: [], verdicts: [], lastStageAt: 0, dirty: true, bubbles: {}, narr: '', lastPanelSub: {}, lastAt: 0};
34
34
  var net = window.CKNet.create($('net'));
35
35
  window.__ck = {S: S, net: net};
36
+ window.__ck.api = {h: h, token: TOKEN, S: S, openModal: function (n) { openModal(n); }, closeModal: function () { closeModal(); }, toast: function (t) { toast(t); }, askText: function (o) { return askText(o); }};
36
37
 
37
38
  var XPAL = ['#FF6B8A', '#8BE04E', '#4F9DFF', '#FF8A4C', '#E0C341', '#B58CFF'], BUILTIN = {director: 1, ba: 1, implement: 1, qc: 1};
38
39
  var DEFAULT_MISSION = {ba: 'Turn the goal into one clear handoff: scope, testable acceptance criteria, out of scope, risks. Afterwards check the finished work against it.', implement: 'Build what the handoff asks for in the project: change the code, run the checks, report what changed and how to verify.', qc: 'Independently review and test the deliverable against the acceptance criteria and give a PASS or FAIL verdict with reasons.'};
@@ -86,7 +87,7 @@
86
87
  function caption() {
87
88
  var st = S.stageKey && S.stageKey.slice(0, 2) === 'x:' ? 'x' : S.stageKey, n = activeSubs(), c;
88
89
  if (S.outcome) c = S.outcome === 'delivered' ? '<b>Mission delivered</b> — báo cáo đã sẵn sàng' : S.outcome === 'declined' ? '<b>Director could not take this request</b> — no team started' : '<b>Run ' + S.outcome + '</b>';
89
- else if (S.waiting) c = '<b>Director</b> is waiting for your answer — nothing is running';
90
+ else if (S.waiting) c = '<b>Director</b> is waiting for your answer — ' + (S.waiting.team ? 'the run is paused' : 'nothing is running');
90
91
  else if (!st) c = 'Chờ nhiệm vụ…';
91
92
  else if (st === 'director-intake') c = '<b>Director</b> đang tiếp nhận và phân tích yêu cầu';
92
93
  else if (st === 'ba-discussion') c = '<b>Team BA</b> đang thảo luận yêu cầu (các BA tranh luận → HANDOFF)';
@@ -139,6 +140,13 @@
139
140
  var cur = r.el.querySelector('.cur'); if (cur) cur.style.display = r.typed ? 'none' : '';
140
141
  });
141
142
  }
143
+ /* The server answers with the version it started with and the one on disk now; when they differ, new screens can hit routes the running process lacks. */
144
+ function staleNotice(running, disk) {
145
+ var el = $('stale'), on = !running || (!!disk && running !== disk);
146
+ if (!on) { if (el) el.remove(); return; }
147
+ if (!el) { el = h('div', {id: 'stale', class: 'stale', role: 'status'}); document.body.appendChild(el); }
148
+ el.textContent = (running ? 'CKit was updated to ' + disk + ' but this process still runs ' + running : 'CKit was updated while this process was running') + '. Stop it with Ctrl+C in its terminal and run ckit again (a live run will be interrupted).';
149
+ }
142
150
  function toast(t) { var el = h('div', {class: 'toast', text: t}); document.body.appendChild(el); setTimeout(function () { el.classList.add('out'); }, 3600); setTimeout(function () { el.remove(); }, 4200); }
143
151
  function shortPath(p) { var parts = String(p || '').split(/[\\/]/).filter(Boolean); return parts.length > 3 ? '…/' + parts.slice(-3).join('/') : String(p || ''); }
144
152
 
@@ -235,7 +243,7 @@
235
243
  feedBanner(e.verdict === 'PASS' ? 'pass' : 'fail', 'Director review · ' + e.verdict + ' — ' + e.summary);
236
244
  comicSimple('director', 'DIRECTOR REVIEW · ' + e.verdict, e.summary);
237
245
  break;
238
- case 'run.waiting': S.waiting = {round: e.round, questions: e.questions, assumptions: e.assumptions}; feedQuestions(e); setNarr('Director needs your answer'); break;
246
+ case 'run.waiting': S.waiting = {round: e.round, questions: e.questions, assumptions: e.assumptions, team: e.team || ''}; feedQuestions(e); setNarr('Director needs your answer'); break;
239
247
  case 'subagent.started':
240
248
  if (a) { a.subs[e.childId] = {kind: e.kind || 'sub', text: e.task, state: 'run'}; net.spawnSub(e.agentId, e.childId, e.kind); feedSub(e.agentId, '◆ spawned ' + (e.kind || 'subagent') + ': ' + e.task); comicSub(e); }
241
249
  break;
@@ -275,9 +283,10 @@
275
283
  function feedQuestions(e) {
276
284
  var qs = String(e.questions || '').split('\n').map(function (l) { return l.replace(/^\s*\d+[.)]\s*/, '').trim(); }).filter(Boolean);
277
285
  var as = e.assumptions ? String(e.assumptions).split('\n').map(function (l) { return l.replace(/^\s*[-*\d.)]+\s*/, '').trim(); }).filter(Boolean) : [];
278
- $('feed').appendChild(h('div', {class: 'qcard'}, [h('b', {text: 'Director needs your answer · round ' + e.round + ' of 3'}), h('ol', {}, qs.map(function (q) { return h('li', {text: q}); })),
286
+ $('feed').appendChild(h('div', {class: 'qcard'}, [h('b', {text: e.team ? 'Director needs your decision · asked by ' + teamLbl(e.team) : 'Director needs your answer · round ' + e.round + ' of 3'}), h('ol', {}, qs.map(function (q) { return h('li', {text: q}); })),
279
287
  as.length ? h('div', {class: 'ml', text: 'IF YOU DO NOT ANSWER, THE DIRECTOR WILL ASSUME'}) : null, as.length ? h('ul', {}, as.map(function (q) { return h('li', {text: q}); })) : null,
280
- h('div', {class: 'qhint', text: as.length ? 'Type your answer below, or choose Proceed with assumptions.' : 'Type your answer below. No team starts until you answer.'})])); feedScroll(); count();
288
+ h('div', {class: 'qhint', text: as.length ? 'Type your answer in the ANSWER box (you can attach files and use @), or choose Proceed with assumptions.' : e.team ? 'Type your answer in the ANSWER box (you can attach files and use @). The run is paused until you answer.' : 'Type your answer in the ANSWER box (you can attach files and use @). No team starts until you answer.'}),
289
+ h('button', {class: 'primary qgo', type: 'button', text: 'Answer now ▸', onclick: function () { $('msg').focus(); }})])); feedScroll(); count();
281
290
  }
282
291
  function feedSub(parent, t) { $('feed').appendChild(h('div', {class: 'fsub', text: '↳ ' + nm(parent) + ' ' + t})); feedScroll(); }
283
292
  function count() { $('feedcount').textContent = S.events.filter(function (e) { return e.type === 'agent.message'; }).length + ' MESSAGES'; }
@@ -341,7 +350,7 @@
341
350
  h('div', {class: 'askbody'}, [h('label', {class: 'ml', text: o.label}), input, err, chips, o.hint ? h('p', {text: o.hint}) : null]),
342
351
  h('footer', {}, [h('span', {class: 'askkeys', text: 'Enter to confirm · Esc to cancel'}), h('button', {type: 'button', text: 'Cancel', onclick: function () { close(null); }}), h('button', {type: 'button', class: 'primary', text: o.okText || 'OK', onclick: ok})])]);
343
352
  card.setAttribute('role', 'dialog'); card.setAttribute('aria-modal', 'true'); card.setAttribute('aria-label', o.title);
344
- var layer = h('div', {class: 'ask'}, [card]);
353
+ var layer = h('div', {class: 'asklayer'}, [card]);
345
354
  layer.addEventListener('mousedown', function (e) { if (e.target === layer) close(null); });
346
355
  layer.addEventListener('keydown', function (e) { if (e.key === 'Escape') { e.stopPropagation(); close(null); } else if (e.key === 'Enter' && e.target === input) { e.preventDefault(); ok(); } });
347
356
  input.addEventListener('input', function () { err.textContent = ''; });
@@ -490,11 +499,11 @@
490
499
  $('active').textContent = S.order.filter(function (i) { return A(i).state === 'thinking'; }).length + activeSubs();
491
500
  $('idleHint').style.display = S.run ? 'none' : ''; $('now').style.display = S.run ? '' : 'none';
492
501
  /* composer: talks to the Director during a run, starts a mission when nothing is running */
493
- var sim = simDefault(), wt = !!(live && S.waiting), mode = wt ? 'wait' + (S.waiting.assumptions ? 'A' : '') : live ? 'live' : sim ? 'sim' : 'real';
502
+ var sim = simDefault(), wt = !!(live && S.waiting), mode = wt ? 'wait' + (S.waiting.assumptions ? 'A' : '') + S.waiting.round + (S.waiting.team || '') : live ? 'live' : sim ? 'sim' : 'real';
494
503
  if (S.cmode !== mode) {
495
504
  S.cmode = mode; $('clabel').textContent = wt ? 'ANSWER → DIRECTOR' : live ? 'OWNER → DIRECTOR' : 'NEW MISSION → DIRECTOR'; $('send').textContent = wt ? 'Send answer ▸' : live ? 'Send ▸' : 'Start ▸'; $('chips').style.display = live && !wt ? '' : 'none';
496
- $('msg').placeholder = wt ? 'Answer the Director…' : live ? 'Message the Director… (Enter to send)' : 'Describe the mission and press Enter to start the team…';
497
- $('cnote').textContent = wt ? 'The Director is waiting for you: no team has started and nothing is running.' : live ? '' : sim ? 'Demo mode: no real agent is configured, so this starts a simulated run.' : 'Starts real agents in ' + shortPath(S.projectRoot); $('cnote').title = S.projectRoot || '';
505
+ $('composer').classList.toggle('wait', wt); $('msg').placeholder = wt ? 'Type your answer and press Enter… (@ for a file, 📎 to attach)' : live ? 'Message the Director… (Enter to send, @ for a file)' : 'Describe the mission and press Enter to start the team… Type @ to point at a file or folder.';
506
+ $('cnote').textContent = wt ? (S.waiting.team ? 'The run is paused: the Director is waiting for your decision.' : 'The Director is waiting for you: no team has started and nothing is running.') : live ? '' : sim ? 'Demo mode: no real agent is configured, so this starts a simulated run.' : 'Starts real agents in ' + shortPath(S.projectRoot); $('cnote').title = S.projectRoot || '';
498
507
  waitButtons(wt); if (wt) setTimeout(function () { $('msg').focus(); }, 30);
499
508
  }
500
509
  var lanes = (S.config && S.config.lanes) || [], sig = live ? '' : lanes.map(function (l) { return l.id + ':' + l.name; }).join('|');
@@ -556,7 +565,7 @@
556
565
  h('div', {class: 'body'}, [h('div', {class: 'ml', text: 'GOAL'}), goal, h('div', {class: 'ml', style: 'margin-top:12px', text: 'WORKSPACE (agents run in this folder)'}), h('div', {class: 'mono', style: 'font-size:12px;word-break:break-all;color:var(--cy)', text: S.projectRoot || ''}), h('div', {class: 'ml', style: 'margin-top:12px', text: 'ATTACHMENTS (any file type; the Director and every team read them)'}), h('div', {style: 'margin:6px 0'}, [h('button', {text: '📎 Attach files', onclick: function () { $('file').click(); }})]), h('div', {class: 'attlist'}), h('label', {style: 'display:flex;gap:8px;align-items:center;margin-top:12px'}, [sim, 'Demo mode (simulated agents, no API cost)'])]),
557
566
  h('footer', {}, [h('button', {text: 'Cancel', onclick: closeModal}), h('button', {class: 'primary', text: 'Start ▸', onclick: function () { startRun(goal.value, sim.checked, laneSel ? laneSel.value : ''); }})])]));
558
567
  if (laneSel) $('modal').querySelector('.body').appendChild(h('div', {style: 'margin-top:12px'}, [h('div', {class: 'ml', text: 'LANE'}), laneSel]));
559
- renderPending(); setTimeout(function () { goal.focus(); }, 30);
568
+ mentionable(goal); renderPending(); setTimeout(function () { goal.focus(); }, 30);
560
569
  }
561
570
  /* attachments waiting to be sent: uploaded as soon as they are picked, claimed by id when the message / mission is sent */
562
571
  var PEND = [];
@@ -608,6 +617,56 @@
608
617
  var ids = chip ? [] : pendingIds(); if (!ids) return;
609
618
  api('POST', '/api/runs/current/message', {text: text, attachments: ids}).then(function (r) { if (r.status !== 200) toast(r.body.error || 'No active run'); else { if (!chip) { $('msg').value = ''; clearPending(); } } });
610
619
  }
620
+ /* "@" mentions: typing @ in a request box lists files and folders of the workspace; the chosen path goes into the text as @path */
621
+ var MENT = null;
622
+ function mentionClose() { if (MENT) { MENT.box.remove(); MENT = null; } }
623
+ function mentionToken(ta) {
624
+ var before = ta.value.slice(0, ta.selectionStart), m = /(^|\s)@(?:"([^"\n]*)|([^\s"]*))$/.exec(before); if (!m) return null;
625
+ var q = m[2] !== undefined ? m[2] : m[3]; return {q: q, start: before.length - q.length - (m[2] !== undefined ? 2 : 1)};
626
+ }
627
+ function mentionPick(ta, f, stay) {
628
+ var t = mentionToken(ta); if (!t) return mentionClose();
629
+ var path = f.path + (f.dir ? '/' : ''), txt = '@' + (/\s/.test(path) ? '"' + path + (stay ? '' : '"') : path) + (stay ? '' : ' ');
630
+ ta.value = ta.value.slice(0, t.start) + txt + ta.value.slice(ta.selectionStart); var pos = t.start + txt.length; ta.setSelectionRange(pos, pos);
631
+ ta.dispatchEvent(new Event('input')); if (!stay) mentionClose();
632
+ }
633
+ function mentionDraw(ta) {
634
+ var M = MENT, r = ta.getBoundingClientRect(); M.box.innerHTML = '';
635
+ M.box.appendChild(h('div', {class: 'menth'}, [h('span', {text: M.q ? 'FILES MATCHING “' + M.q + '”' : 'FILES IN ' + (S.projectRoot ? shortPath(S.projectRoot) : 'THIS FOLDER')}), h('span', {text: '↑↓ move · Enter pick · Tab open folder · Esc close'})]));
636
+ if (!M.items.length) M.box.appendChild(h('div', {class: 'mentnone', text: M.loading ? 'Searching…' : M.error || 'No file or folder matches. Keep typing, or press Esc.'}));
637
+ M.items.forEach(function (f, i) {
638
+ var cut = f.path.lastIndexOf('/'), row = h('div', {class: 'mentrow' + (i === M.idx ? ' on' : '')}, [h('span', {class: 'menti', text: f.dir ? '▸' : '·'}), h('b', {text: f.path.slice(cut + 1) + (f.dir ? '/' : '')}), h('small', {text: cut >= 0 ? f.path.slice(0, cut) : ''})]);
639
+ row.addEventListener('mousedown', function (ev) { ev.preventDefault(); mentionPick(ta, f, false); });
640
+ M.box.appendChild(row); if (i === M.idx) setTimeout(function () { row.scrollIntoView({block: 'nearest'}); }, 0);
641
+ });
642
+ var w = Math.max(360, Math.min(560, window.innerWidth - 24)); M.box.style.width = w + 'px';
643
+ M.box.style.left = Math.max(12, Math.min(r.left, window.innerWidth - w - 12)) + 'px'; M.box.style.bottom = (window.innerHeight - r.top + 6) + 'px'; M.box.style.maxHeight = Math.max(140, Math.min(340, r.top - 18)) + 'px';
644
+ }
645
+ function mentionSync(ta) {
646
+ var t = mentionToken(ta); if (!t) return mentionClose();
647
+ if (!MENT || MENT.ta !== ta) { mentionClose(); MENT = {ta: ta, box: h('div', {class: 'ment'}), items: [], idx: 0, q: '', seq: 0, loading: true, error: ''}; document.body.appendChild(MENT.box); }
648
+ var M = MENT, seq = ++M.seq; M.q = t.q; M.loading = true; mentionDraw(ta);
649
+ clearTimeout(M.timer); M.timer = setTimeout(function () {
650
+ api('GET', '/api/files?q=' + encodeURIComponent(t.q)).then(function (r) { if (MENT !== M || M.seq !== seq) return; M.loading = false; M.error = r.status === 200 ? '' : (r.body.error || 'Could not list files.'); M.items = r.status === 200 ? r.body.files : []; M.idx = 0; mentionDraw(ta); });
651
+ }, 70);
652
+ }
653
+ function mentionable(ta) {
654
+ ta.addEventListener('input', function () { mentionSync(ta); });
655
+ ta.addEventListener('click', function () { if (MENT) mentionSync(ta); });
656
+ ta.addEventListener('blur', function () { setTimeout(function () { if (MENT && MENT.ta === ta) mentionClose(); }, 120); });
657
+ ta.addEventListener('keydown', function (ev) {
658
+ if (!MENT || MENT.ta !== ta) return; var M = MENT, n = M.items.length, eat = true;
659
+ if (ev.key === 'Escape') mentionClose();
660
+ else if (ev.key === 'ArrowDown' && n) { M.idx = (M.idx + 1) % n; mentionDraw(ta); }
661
+ else if (ev.key === 'ArrowUp' && n) { M.idx = (M.idx + n - 1) % n; mentionDraw(ta); }
662
+ else if (ev.key === 'Enter' && !ev.shiftKey && n) mentionPick(ta, M.items[M.idx], false);
663
+ else if (ev.key === 'Tab' && n) mentionPick(ta, M.items[M.idx], M.items[M.idx].dir);
664
+ else if (ev.key === 'Enter' && !ev.shiftKey) mentionClose();
665
+ else eat = false;
666
+ if (eat) { ev.preventDefault(); ev.stopImmediatePropagation(); }
667
+ }, true);
668
+ }
669
+ mentionable($('msg'));
611
670
  /* Enhance for the first request: one turn of the Director's CLI proposes a clearer brief; nothing is replaced or started until the owner says so */
612
671
  var REQ = {busy: false, applied: null, before: ''};
613
672
  function syncEnh() {
@@ -959,7 +1018,7 @@
959
1018
  return;
960
1019
  }
961
1020
  if (r.status !== 200) { document.body.innerHTML = '<p style="padding:40px;color:#F05668;font-family:monospace">Missing or invalid session token. Open the URL printed by `ckit gui`.</p>'; return; }
962
- S.config = r.body.config; S.configExists = r.body.configExists !== false; S.projectRoot = r.body.projectRoot || ''; (function (root) { var name = root.split(/[\\/]/).filter(Boolean).pop() || root, ws = $('cwd').parentNode; $('cwdn').textContent = name; $('cwd').textContent = '\u200e' + root; document.title = name + ' · CKit'; ws.title = 'Agents read and write files in this folder (click to copy):\n' + root; ws.onclick = function () { if (navigator.clipboard) navigator.clipboard.writeText(root).then(function () { $('cwdn').textContent = 'copied ✓'; setTimeout(function () { $('cwdn').textContent = name; }, 1200); }, function () {}); }; })(S.projectRoot); S.simulatedDefault = r.body.simulatedDefault; S.run = r.body.run ? {runId: r.body.run.runId, running: r.body.run.running, goal: r.body.run.goal} : null;
1021
+ S.config = r.body.config; S.configExists = r.body.configExists !== false; S.projectRoot = r.body.projectRoot || ''; staleNotice(r.body.version, r.body.diskVersion); (function (root) { var name = root.split(/[\\/]/).filter(Boolean).pop() || root, ws = $('cwd').parentNode; $('cwdn').textContent = name; $('cwd').textContent = '\u200e' + root; document.title = name + ' · CKit'; ws.title = 'Open workspace files\n' + root; ws.style.cursor = 'pointer'; ws.setAttribute('role', 'button'); ws.tabIndex = 0; ws.onclick = function () { if (window.__ckExplorer) window.__ckExplorer.open(''); }; ws.onkeydown = function (e) { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); ws.onclick(); } }; })(S.projectRoot); S.simulatedDefault = r.body.simulatedDefault; S.run = r.body.run ? {runId: r.body.run.runId, running: r.body.run.running, goal: r.body.run.goal} : null;
963
1022
  S.replay = !!(r.body.run && r.body.run.goal === '(replay)');
964
1023
  setupAgents(S.config);
965
1024
  // First run (no .ckit/team.json, nothing running): land on Config so setup starts in the GUI.
@@ -0,0 +1,373 @@
1
+ /* Workspace explorer popup: browse, preview, upload, create folders, rename, move to trash; polls the open folder. Vanilla JS, loaded after app.js. */
2
+ (function () {
3
+ 'use strict';
4
+ var ck = window.__ck && window.__ck.api; if (!ck) return;
5
+ var h0 = ck.h, TOKEN = ck.token, S = ck.S, $ = function (id) { return document.getElementById(id); };
6
+ /* ck.h sets unknown keys as properties; data-* / aria-* / role must be real attributes */
7
+ function h(tag, attrs, kids) {
8
+ var plain = {}, special = {};
9
+ Object.keys(attrs || {}).forEach(function (k) { if (/^(data-|aria-)/.test(k) || k === 'role') special[k] = attrs[k]; else plain[k] = attrs[k]; });
10
+ var e = h0(tag, plain, kids); Object.keys(special).forEach(function (k) { e.setAttribute(k, special[k]); }); return e;
11
+ }
12
+ var EX = null, POLL_MS = 2000, PREVIEW_TEXT_MAX = 2 * 1048576;
13
+ var IMG = /\.(png|jpe?g|gif|webp)$/i, DOC = /\.(pdf|docx?|xlsx?|pptx?|md|markdown|txt|csv|drawio|rtf)$/i, CODE = /\.(m?[jt]sx?|cjs|json|ya?ml|toml|html?|css|scss|py|rb|go|rs|java|kt|c|h|cpp|cs|php|sh|sql|xml|svg|vue)$/i;
14
+ var TEXTY = /\.(txt|md|markdown|json|jsonl|ya?ml|toml|ini|cfg|conf|csv|tsv|log|xml|html?|svg|css|scss|less|m?[jt]sx?|cjs|py|rb|go|rs|java|kt|c|h|cpp|hpp|cs|php|sh|zsh|bat|sql|vue|svelte|drawio|gitignore|editorconfig|lock)$/i;
15
+
16
+ function kindOf(e) { return e.dir ? 'dir' : IMG.test(e.name) ? 'img' : DOC.test(e.name) ? 'doc' : CODE.test(e.name) ? 'code' : 'oth'; }
17
+ var GLYPH = {dir: '▸', img: '◩', doc: '≡', code: '</>', oth: '·'};
18
+ function size(n) { return n >= 1073741824 ? (n / 1073741824).toFixed(1) + ' GB' : n >= 1048576 ? (n / 1048576).toFixed(1) + ' MB' : n >= 1024 ? Math.round(n / 1024) + ' KB' : n + ' B'; }
19
+ function ago(ms) {
20
+ var s = Math.max(0, Math.round((Date.now() - ms) / 1000));
21
+ if (s < 10) return 'just now'; if (s < 60) return s + ' sec ago'; var m = Math.round(s / 60); if (m < 60) return m + ' min ago';
22
+ var hr = Math.round(m / 60); if (hr < 24) return hr + ' hr ago'; var d = Math.round(hr / 24); if (d < 30) return d + (d === 1 ? ' day ago' : ' days ago');
23
+ return new Date(ms).toLocaleDateString();
24
+ }
25
+ var join = function (a, b) { return a ? a + '/' + b : b; };
26
+ var parentOf = function (p) { var i = p.lastIndexOf('/'); return i < 0 ? '' : p.slice(0, i); };
27
+ var wsName = function () { return (S.projectRoot || '').split(/[\\/]/).filter(Boolean).pop() || 'Workspace'; };
28
+ var fileUrl = function (path, dl) { return '/api/fs/file?path=' + encodeURIComponent(path) + (dl ? '&download=1' : '') + '&t=' + encodeURIComponent(TOKEN); };
29
+
30
+ /* The root folder always exists, so 404 on it means the running ckit process predates this screen (updated while running). */
31
+ var RESTART = 'This ckit process is older than the screen you opened (CKit was updated while it was running). Stop it with Ctrl+C in its terminal and run ckit again.';
32
+ function fs(method, path, body) {
33
+ return fetch(path, {method: method, headers: {'x-ckit-token': TOKEN, 'content-type': 'application/json'}, body: body === undefined ? undefined : JSON.stringify(body)})
34
+ .then(function (r) { return r.json().catch(function () { return {}; }).then(function (j) { return {status: r.status, body: j}; }); }, function () { return {status: 0, body: {error: 'Cannot reach CKit; check that ckit is still running.'}}; });
35
+ }
36
+
37
+ /* confirm dialog, same look as askText */
38
+ function askConfirm(o) {
39
+ return new Promise(function (done) {
40
+ var close = function (v) { layer.remove(); done(v); };
41
+ var okb = h('button', {type: 'button', class: 'primary', text: o.okText, onclick: function () { close(true); }});
42
+ var card = h('div', {class: 'askcard'}, [h('header', {}, [h('b', {text: o.title}), h('button', {class: 'askx', type: 'button', text: '✕', title: 'Cancel', onclick: function () { close(false); }})]),
43
+ h('div', {class: 'askbody'}, [h('p', {style: 'margin:4px 0 8px;font-size:13px;color:var(--tx)', text: o.text}), o.hint ? h('p', {text: o.hint}) : null]),
44
+ h('footer', {}, [h('span', {class: 'askkeys', text: 'Enter to confirm · Esc to cancel'}), h('button', {type: 'button', text: 'Cancel', onclick: function () { close(false); }}), okb])]);
45
+ card.setAttribute('role', 'dialog'); card.setAttribute('aria-modal', 'true');
46
+ var layer = h('div', {class: 'asklayer'}, [card]);
47
+ layer.addEventListener('mousedown', function (e) { if (e.target === layer) close(false); });
48
+ layer.addEventListener('keydown', function (e) { if (e.key === 'Escape') { e.stopPropagation(); close(false); } else if (e.key === 'Enter') { e.preventDefault(); e.stopPropagation(); close(true); } });
49
+ document.body.appendChild(layer); okb.focus();
50
+ });
51
+ }
52
+
53
+ /* ---------- open / close ---------- */
54
+ function open(startPath) {
55
+ if (EX) return;
56
+ EX = {path: startPath || '', entries: [], sig: '', sel: [], anchor: null, sort: {k: 'name', dir: 1}, filter: '', base: {}, hist: {}, flash: {}, uploads: [], prev: null, prevTok: 0, busy: false, err: '', opened: Date.now(), timer: 0, dropDir: null, rootNames: null, loaded: false};
57
+ var up = h('input', {type: 'file', multiple: true, hidden: true}); up.addEventListener('change', function () { upload(up.files, uploadDir()); up.value = ''; });
58
+ EX.el = {};
59
+ var E = EX.el;
60
+ E.bc = h('div', {class: 'exbc'}); E.filter = h('input', {class: 'exfilter', placeholder: 'Filter this folder…', spellcheck: false, autocomplete: 'off', 'aria-label': 'Filter files in this folder'});
61
+ E.filter.addEventListener('input', function () { EX.filter = E.filter.value.trim().toLowerCase(); renderList(); });
62
+ E.btnRef = h('button', {type: 'button', class: 'exref', text: '+ References folder', title: 'Files you put here stay in the project; point agents at them with @references/…', onclick: makeReferences});
63
+ E.tools = h('div', {class: 'extool'}, [h('button', {type: 'button', class: 'exup', title: 'Go up one folder (Backspace)', text: '↑', onclick: goUp}), E.bc, E.filter,
64
+ h('button', {type: 'button', text: '+ New folder', onclick: newFolder}), (E.btnUp = h('button', {type: 'button', class: 'primary exupl', text: '⬆ Upload', onclick: function () { up.click(); }})), E.btnRef, up]);
65
+ E.head = h('div', {class: 'exrow exhead'}, [h('span'), sortHead('name', 'Name'), sortHead('size', 'Size'), sortHead('mtime', 'Modified'), h('span')]);
66
+ E.rows = h('div', {class: 'exrows', tabIndex: 0, role: 'listbox', 'aria-label': 'Files and folders'});
67
+ E.rows.addEventListener('click', function (ev) { if (ev.target === E.rows) { EX.sel = []; syncSel(); } });
68
+ E.empty = h('div', {class: 'exempty'});
69
+ E.list = h('div', {class: 'exlist'}, [E.head, E.rows, E.empty, h('div', {class: 'exdrop', text: 'Drop to upload here'})]);
70
+ E.prev = h('aside', {class: 'exprev'});
71
+ E.ups = h('div', {class: 'exups'});
72
+ E.status = h('span', {class: 'exstat'}); E.hint = h('span', {class: 'exhint', text: 'Files in references/ stay in the project; point agents at them with @references/…'});
73
+ E.live = h('span', {class: 'exlive', title: 'This list refreshes by itself every 2 seconds'}, [h('i'), 'live']);
74
+ var dlg = h('div', {class: 'dlg wide exdlg', role: 'dialog', 'aria-modal': 'true', 'aria-label': 'Workspace files'}, [
75
+ h('header', {}, [h('b', {text: 'WORKSPACE FILES'}), h('span', {class: 'exroot mono', title: S.projectRoot || '', text: '‎' + (S.projectRoot || '')}), h('button', {type: 'button', class: 'excopy', text: 'Copy path', onclick: copyPath}), E.live, h('button', {type: 'button', text: '✕', title: 'Close (Esc)', onclick: close})]),
76
+ E.tools, h('div', {class: 'exmain'}, [E.list, E.prev]), E.ups, h('footer', {class: 'exfoot'}, [E.status, E.hint])]);
77
+ E.dlg = dlg; ck.openModal(dlg);
78
+ EX.obs = new MutationObserver(function () { if (EX && (M.hidden || !M.contains(E.dlg))) close(); }); EX.obs.observe(M, {childList: true, attributes: true, attributeFilter: ['hidden']});
79
+ document.addEventListener('keydown', onKey, true);
80
+ document.addEventListener('visibilitychange', onVis);
81
+ EX.timer = setInterval(poll, POLL_MS);
82
+ renderPrev(); load(EX.path, true);
83
+ setTimeout(function () { if (EX) E.rows.focus(); }, 30);
84
+ }
85
+ function close() {
86
+ if (!EX) return;
87
+ EX.obs.disconnect(); clearInterval(EX.timer); document.removeEventListener('keydown', onKey, true); document.removeEventListener('visibilitychange', onVis);
88
+ if (EX.prevUrl) URL.revokeObjectURL(EX.prevUrl);
89
+ EX = null; ck.closeModal();
90
+ }
91
+ function copyPath() { if (navigator.clipboard) navigator.clipboard.writeText(S.projectRoot || '').then(function () { ck.toast('Folder path copied'); }, function () {}); }
92
+
93
+ /* ---------- data ---------- */
94
+ function load(path, first) {
95
+ if (!EX) return; var my = EX; my.busy = true;
96
+ return fs('GET', '/api/fs/list?path=' + encodeURIComponent(path)).then(function (r) {
97
+ if (EX !== my) return; my.busy = false;
98
+ if (r.status === 200) { my.err = ''; if (path !== my.path || first) { my.path = path; } apply(r.body, true); return; }
99
+ if (r.status === 404 && path) { ck.toast('That folder is gone; showing its parent.'); return load(parentOf(path)); }
100
+ my.err = r.status === 404 && !path ? RESTART : (r.body.error || 'Could not read this folder.'); if (my.loaded) { setStatus(); } else { renderList(); }
101
+ });
102
+ }
103
+ function poll() {
104
+ var my = EX; if (!my || my.busy || document.hidden || my.dragging) return; my.busy = true;
105
+ fs('GET', '/api/fs/list?path=' + encodeURIComponent(my.path)).then(function (r) {
106
+ if (EX !== my) return; my.busy = false;
107
+ if (r.status === 200) { my.err = ''; if (r.body.sig !== my.sig || r.body.path !== my.path) apply(r.body, false); else refreshAges(); setStatus(); }
108
+ else if (r.status === 404 && my.path) { ck.toast('That folder is gone; showing its parent.'); load(parentOf(my.path)); }
109
+ else { my.err = r.body.error || 'Connection lost; retrying…'; setStatus(); }
110
+ });
111
+ }
112
+ function onVis() { if (!document.hidden) poll(); }
113
+ function apply(body, navigated) {
114
+ var prevNames = {}; EX.entries.forEach(function (e) { prevNames[e.name] = e; });
115
+ var key = body.path, base = EX.base[key];
116
+ if (!base) { base = EX.base[key] = {}; body.entries.forEach(function (e) { base[e.name] = e.mtime; }); }
117
+ var fl = EX.flash[key] || (EX.flash[key] = {});
118
+ body.entries.forEach(function (e) {
119
+ if (!(e.name in base)) { fl[e.name] = 'new'; }
120
+ else if (base[e.name] !== e.mtime && fl[e.name] !== 'new') { fl[e.name] = 'changed'; }
121
+ });
122
+ var fresh = {};
123
+ if (!navigated || EX.loaded) body.entries.forEach(function (e) { var p = prevNames[e.name]; if (EX.loaded && EX.lastPath === key && (!p || p.mtime !== e.mtime)) fresh[e.name] = 1; });
124
+ EX.entries = body.entries; EX.sig = body.sig; EX.truncated = body.truncated; EX.pulse = fresh;
125
+ var pathChanged = EX.lastPath !== key; EX.lastPath = key; EX.loaded = true;
126
+ var keep = EX.sel.filter(function (n) { return body.entries.some(function (e) { return e.name === n; }); }); if (pathChanged) keep = []; EX.sel = keep;
127
+ if (pathChanged) EX.el.filter.value = '', EX.filter = '';
128
+ renderBc(); renderList(pathChanged); syncSel(); renderRefBtn(); if (EX.prev && EX.prev.path && !body.entries.some(function (e) { return join(key, e.name) === EX.prev.path; }) && parentOf(EX.prev.path) === key) { EX.prev = null; renderPrev(); } else if (EX.prev && EX.prev.path && parentOf(EX.prev.path) === key) { var pe = body.entries.filter(function (e) { return join(key, e.name) === EX.prev.path; })[0]; if (pe && pe.mtime !== EX.prev.mtime) showPreview(pe); }
129
+ }
130
+ function renderRefBtn() {
131
+ var E = EX.el; if (EX.path === '') EX.rootNames = EX.entries.map(function (e) { return e.name; });
132
+ E.btnRef.hidden = !(EX.rootNames && EX.rootNames.indexOf('references') < 0);
133
+ }
134
+
135
+ /* ---------- rendering ---------- */
136
+ function sortHead(k, label) {
137
+ return h('button', {type: 'button', class: 'exsort', 'data-k': k, text: label, title: 'Sort by ' + label.toLowerCase(), onclick: function () { if (EX.sort.k === k) EX.sort.dir = -EX.sort.dir; else EX.sort = {k: k, dir: k === 'mtime' ? -1 : 1}; renderList(); }});
138
+ }
139
+ function renderBc() {
140
+ var E = EX.el; E.bc.innerHTML = '';
141
+ var segs = EX.path ? EX.path.split('/') : [], acc = '';
142
+ var mk = function (label, p, last) {
143
+ var b = h('button', {type: 'button', class: 'excrumb' + (last ? ' cur' : ''), text: label, title: p || S.projectRoot || '', onclick: function () { go(p); }});
144
+ b.addEventListener('dragover', function (ev) { if (ev.dataTransfer && Array.prototype.indexOf.call(ev.dataTransfer.types || [], 'application/x-ckit-move') >= 0 && !last) { ev.preventDefault(); b.classList.add('dropto'); } });
145
+ b.addEventListener('dragleave', function () { b.classList.remove('dropto'); });
146
+ b.addEventListener('drop', function (ev) { b.classList.remove('dropto'); var mv = ev.dataTransfer.getData('application/x-ckit-move'); if (mv) { ev.preventDefault(); ev.stopPropagation(); moveInto(JSON.parse(mv), p); } });
147
+ return b;
148
+ };
149
+ E.bc.appendChild(mk(wsName(), '', segs.length === 0));
150
+ segs.forEach(function (s, i) { acc = join(acc, s); E.bc.appendChild(h('span', {class: 'exsep', text: '›'})); E.bc.appendChild(mk(s, acc, i === segs.length - 1)); });
151
+ }
152
+ function visible() {
153
+ var f = EX.filter, k = EX.sort.k, d = EX.sort.dir;
154
+ var a = EX.entries.filter(function (e) { return !f || e.name.toLowerCase().indexOf(f) >= 0; });
155
+ a.sort(function (x, y) {
156
+ if (x.dir !== y.dir) return x.dir ? -1 : 1;
157
+ var c = k === 'size' ? x.size - y.size : k === 'mtime' ? x.mtime - y.mtime : x.name.localeCompare(y.name, undefined, {numeric: true, sensitivity: 'base'});
158
+ return (c || x.name.localeCompare(y.name, undefined, {numeric: true})) * (k === 'name' || c ? d : 1);
159
+ });
160
+ return a;
161
+ }
162
+ function badgeFor(e) {
163
+ var f = (EX.flash[EX.path] || {})[e.name];
164
+ if (f === 'new') return h('span', {class: 'exbadge new', text: 'NEW', title: 'Appeared since you opened this window'});
165
+ if (f === 'changed') return h('span', {class: 'exbadge chg', text: 'CHANGED', title: 'Changed since you opened this window'});
166
+ if (S.run && S.run.running && S.started && e.mtime >= S.started && !e.dir) return h('span', {class: 'exbadge run', text: 'THIS RUN', title: 'Written after the current run started'});
167
+ return null;
168
+ }
169
+ function renderList(resetScroll) {
170
+ var E = EX.el, top = E.rows.scrollTop, list = visible(), focus = document.activeElement && E.rows.contains(document.activeElement);
171
+ Array.prototype.forEach.call(E.head.querySelectorAll('.exsort'), function (b) { var on = b.getAttribute('data-k') === EX.sort.k; b.classList.toggle('on', on); b.setAttribute('data-arrow', on ? (EX.sort.dir > 0 ? '▲' : '▼') : ''); });
172
+ var frag = document.createDocumentFragment();
173
+ list.forEach(function (e) { frag.appendChild(row(e)); });
174
+ E.rows.innerHTML = ''; E.rows.appendChild(frag); E.rows.scrollTop = resetScroll ? 0 : top;
175
+ var none = !list.length;
176
+ E.empty.hidden = !none; E.head.hidden = none && !EX.entries.length && !EX.err;
177
+ if (none) {
178
+ E.empty.innerHTML = '';
179
+ if (EX.err) E.empty.appendChild(h('div', {class: 'exetitle err', text: EX.err}));
180
+ else if (EX.entries.length) E.empty.appendChild(h('div', {class: 'exetitle', text: 'Nothing here matches “' + EX.el.filter.value + '”.'}));
181
+ else { E.empty.appendChild(h('div', {class: 'exebig', text: '▸'})); E.empty.appendChild(h('div', {class: 'exetitle', text: 'This folder is empty'})); E.empty.appendChild(h('div', {class: 'exesub', text: 'Drag files here from your computer, or press Upload. Files the agents create will show up here by themselves.'})); }
182
+ }
183
+ syncSel(); setStatus();
184
+ if (focus) E.rows.focus();
185
+ }
186
+ function actBtn(txt, title, fn) { var b = h('button', {type: 'button', class: 'exact', text: txt, title: title, tabIndex: -1}); b.addEventListener('click', function (ev) { ev.stopPropagation(); fn(); }); b.addEventListener('dblclick', function (ev) { ev.stopPropagation(); }); return b; }
187
+ function row(e) {
188
+ var k = kindOf(e), pulse = EX.pulse && EX.pulse[e.name];
189
+ var r = h('div', {class: 'exrow exitem' + (pulse ? ' pulse' : ''), role: 'option', 'data-name': e.name, draggable: true, title: e.name}, [
190
+ h('span', {class: 'exic ' + k, text: GLYPH[k]}), h('span', {class: 'exname'}, [h('span', {class: 'exn', text: e.name}), badgeFor(e)]),
191
+ h('span', {class: 'exsize', text: e.dir ? '—' : size(e.size)}), h('span', {class: 'exmod', 'data-m': e.mtime, text: ago(e.mtime)}),
192
+ h('span', {class: 'exacts'}, [e.dir ? null : actBtn('⬇', 'Download', function () { download(e); }), actBtn('@', 'Mention in request', function () { mention(e); }), actBtn('✎', 'Rename (F2)', function () { rename(e); }), actBtn('🗑', 'Move to trash (Delete, or ⌘/Ctrl+Backspace)', function () { trash([e]); })])]);
193
+ r.addEventListener('click', function (ev) { select(e.name, ev); EX.el.rows.focus(); });
194
+ r.addEventListener('dblclick', function () { openItem(e); });
195
+ r.addEventListener('dragstart', function (ev) { if (EX.sel.indexOf(e.name) < 0) { EX.sel = [e.name]; syncSel(); } ev.dataTransfer.setData('application/x-ckit-move', JSON.stringify(EX.sel.map(function (n) { return join(EX.path, n); }))); ev.dataTransfer.effectAllowed = 'move'; EX.dragging = true; });
196
+ r.addEventListener('dragend', function () { EX.dragging = false; });
197
+ return r;
198
+ }
199
+ function refreshAges() { Array.prototype.forEach.call(EX.el.rows.querySelectorAll('.exmod'), function (c) { var t = ago(Number(c.getAttribute('data-m'))); if (c.textContent !== t) c.textContent = t; }); }
200
+ function setStatus() {
201
+ var E = EX.el, dirs = EX.entries.filter(function (e) { return e.dir; }).length, files = EX.entries.length - dirs;
202
+ var sel = EX.sel.length ? ' · ' + EX.sel.length + ' selected' : '';
203
+ E.status.textContent = EX.err ? EX.err : (dirs + (dirs === 1 ? ' folder' : ' folders') + ', ' + files + (files === 1 ? ' file' : ' files') + sel + (EX.truncated ? ' · showing the first 5000 items' : ''));
204
+ E.status.classList.toggle('err', !!EX.err); E.live.classList.toggle('off', !!EX.err); syncUpload();
205
+ }
206
+ function byName(n) { return EX.entries.filter(function (e) { return e.name === n; })[0]; }
207
+ /* The Upload button targets the one selected folder; with no folder selected (or several items) it targets the folder being shown. */
208
+ function uploadDir() { var e = EX.sel.length === 1 ? byName(EX.sel[0]) : null; return e && e.dir ? join(EX.path, e.name) : EX.path; }
209
+ function syncUpload() { var b = EX.el.btnUp; if (!b) return; var d = uploadDir(), name = d ? d.slice(d.lastIndexOf('/') + 1) : wsName(); b.textContent = '⬆ Upload to ' + name + '/'; b.title = 'Files go into ' + (d ? wsName() + '/' + d : wsName() + ' (the workspace folder)') + '. Select one folder first to upload into it.'; }
210
+ function syncSel() {
211
+ Array.prototype.forEach.call(EX.el.rows.children, function (r) { var on = EX.sel.indexOf(r.getAttribute('data-name')) >= 0; r.classList.toggle('sel', on); r.setAttribute('aria-selected', on ? 'true' : 'false'); });
212
+ setStatus();
213
+ }
214
+ function select(name, ev) {
215
+ var names = visible().map(function (e) { return e.name; });
216
+ if (ev && ev.shiftKey && EX.anchor && names.indexOf(EX.anchor) >= 0) { var a = names.indexOf(EX.anchor), b = names.indexOf(name); EX.sel = names.slice(Math.min(a, b), Math.max(a, b) + 1); }
217
+ else if (ev && (ev.metaKey || ev.ctrlKey)) { var i = EX.sel.indexOf(name); if (i >= 0) EX.sel.splice(i, 1); else EX.sel.push(name); EX.anchor = name; }
218
+ else { EX.sel = [name]; EX.anchor = name; }
219
+ syncSel();
220
+ var one = EX.sel.length === 1 ? byName(EX.sel[0]) : null; if (one && !one.dir) showPreview(one); else if (!one && EX.prev) { EX.prev = null; renderPrev(); } else if (one && one.dir && EX.prev) { EX.prev = null; renderPrev(); }
221
+ var r = EX.el.rows.querySelector('[data-name="' + (window.CSS && CSS.escape ? CSS.escape(name) : name.replace(/"/g, '\\"')) + '"]'); if (r && r.scrollIntoView) r.scrollIntoView({block: 'nearest'});
222
+ }
223
+
224
+ /* ---------- preview ---------- */
225
+ function renderPrev() {
226
+ var E = EX.el, p = EX.prev; E.prev.innerHTML = ''; E.dlg.classList.toggle('hasprev', !!p);
227
+ if (EX.prevUrl) { URL.revokeObjectURL(EX.prevUrl); EX.prevUrl = null; }
228
+ if (!p) { E.prev.appendChild(h('div', {class: 'exnoprev'}, [h('div', {class: 'exebig', text: '≡'}), h('div', {text: 'Select a file to preview it here.'}), h('div', {class: 'exesub', text: 'Double-click a folder to open it.'})])); return; }
229
+ var path = p.path;
230
+ E.prev.appendChild(h('div', {class: 'exph'}, [h('b', {class: 'exphn', text: p.name, title: path}), h('button', {type: 'button', class: 'askx', text: '✕', title: 'Close preview (Esc)', onclick: closePrev})]));
231
+ E.prev.appendChild(h('div', {class: 'exmeta'}, [h('span', {text: size(p.size)}), h('span', {text: 'modified ' + ago(p.mtime)})]));
232
+ E.prev.appendChild(h('div', {class: 'exbtns'}, [h('a', {class: 'btn', href: fileUrl(path, true), text: '⬇ Download', download: p.name}), h('button', {type: 'button', text: '@ Mention in request', onclick: function () { mention(p); }})]));
233
+ E.prevBody = h('div', {class: 'exbody'}); E.prev.appendChild(E.prevBody);
234
+ }
235
+ function closePrev() { EX.prev = null; EX.prevTok++; renderPrev(); }
236
+ function showPreview(e) {
237
+ var path = join(EX.path, e.name), tok = ++EX.prevTok; EX.prev = {path: path, name: e.name, size: e.size, mtime: e.mtime}; renderPrev();
238
+ var body = EX.el.prevBody, other = function (msg) { body.innerHTML = ''; body.appendChild(h('div', {class: 'exnoprev'}, [h('div', {class: 'exebig', text: GLYPH[kindOf(e)]}), h('div', {text: msg})])); };
239
+ if (IMG.test(e.name)) {
240
+ if (e.size > 30 * 1048576) return other('This image is large (' + size(e.size) + '). Use Download to open it.');
241
+ body.appendChild(h('div', {class: 'exload', text: 'Loading…'}));
242
+ fetch(fileUrl(path)).then(function (r) { return r.ok ? r.blob() : Promise.reject(); }).then(function (b) { if (!EX || EX.prevTok !== tok) return; EX.prevUrl = URL.createObjectURL(b); body.innerHTML = ''; body.appendChild(h('img', {class: 'eximg', src: EX.prevUrl, alt: e.name})); }, function () { if (EX && EX.prevTok === tok) other('Could not load this image.'); });
243
+ } else if (/\.pdf$/i.test(e.name)) {
244
+ body.appendChild(h('div', {class: 'exnoprev'}, [h('div', {class: 'exebig', text: '≡'}), h('div', {text: 'PDF · ' + size(e.size)}), h('a', {class: 'btn primary', href: fileUrl(path), target: '_blank', rel: 'noopener', text: 'Open in a new tab'})]));
245
+ } else if (TEXTY.test(e.name) || (!/\./.test(e.name.slice(1)) && e.size < PREVIEW_TEXT_MAX)) {
246
+ if (e.size > PREVIEW_TEXT_MAX) return other('This file is large (' + size(e.size) + '). Use Download to read it.');
247
+ body.appendChild(h('div', {class: 'exload', text: 'Loading…'}));
248
+ fetch(fileUrl(path)).then(function (r) { return r.ok ? r.text() : Promise.reject(); }).then(function (t) { if (!EX || EX.prevTok !== tok) return; body.innerHTML = ''; body.appendChild(h('pre', {class: 'extext', text: t.length ? t : '(This file is empty.)'})); }, function () { if (EX && EX.prevTok === tok) other('No preview for this file. Use Download.'); });
249
+ } else other('No preview for this type of file (' + size(e.size) + '). Use Download to open it.');
250
+ }
251
+
252
+ /* ---------- actions ---------- */
253
+ function go(path) { if (!EX) return; EX.prev = null; EX.sel = []; renderPrev(); load(path); }
254
+ function goUp() { if (EX.path) go(parentOf(EX.path)); }
255
+ function openItem(e) { if (e.dir) go(join(EX.path, e.name)); else showPreview(e); }
256
+ function download(e) { var a = h('a', {href: fileUrl(join(EX.path, e.name), true), download: e.name}); document.body.appendChild(a); a.click(); a.remove(); }
257
+ function mention(e) {
258
+ var path = join(EX.path, e.name) + (e.dir ? '/' : ''), msg = $('msg'), txt = '@' + (/\s/.test(path) ? '"' + path + '"' : path) + ' ';
259
+ var v = msg.value; msg.value = v + (v && !/\s$/.test(v) ? ' ' : '') + txt; close(); msg.focus(); msg.setSelectionRange(msg.value.length, msg.value.length); msg.dispatchEvent(new Event('input', {bubbles: true}));
260
+ }
261
+ function nameCheck(v) { return /[\\/]/.test(v) ? 'A name cannot contain slashes.' : /[\u0000-\u001f]/.test(v) ? 'Remove the hidden characters from the name.' : v === '.' || v === '..' ? 'Choose a different name.' : ''; }
262
+ function newFolder() {
263
+ ck.askText({title: 'New folder', label: 'Folder name', placeholder: 'e.g. references', okText: 'Create folder', hint: 'It is created inside “' + (EX.path || wsName()) + '”.', check: nameCheck}).then(function (n) {
264
+ if (!n || !EX) return; var p = join(EX.path, n);
265
+ fs('POST', '/api/fs/mkdir', {path: p}).then(function (r) { if (r.status !== 200) return ck.toast(r.body.error || 'Could not create the folder.'); ck.toast('Folder created'); load(EX.path).then(function () { if (EX) { EX.sel = [n]; syncSel(); } }); });
266
+ });
267
+ }
268
+ function makeReferences() {
269
+ fs('POST', '/api/fs/mkdir', {path: 'references'}).then(function (r) { if (r.status !== 200 && r.status !== 409) return ck.toast(r.body.error || 'Could not create the folder.'); if (EX) { EX.rootNames = (EX.rootNames || []).concat('references'); go('references'); } });
270
+ }
271
+ function rename(e) {
272
+ ck.askText({title: 'Rename', label: 'New name', value: e.name, okText: 'Rename', check: function (v) { return nameCheck(v) || (v === e.name ? 'That is the current name; type a new one.' : ''); }}).then(function (n) {
273
+ if (!n || !EX) return; var base = EX.path;
274
+ fs('POST', '/api/fs/rename', {from: join(base, e.name), to: join(base, n)}).then(function (r) { if (r.status !== 200) return ck.toast(r.body.error || 'Could not rename.'); if (EX) { EX.prev = null; renderPrev(); load(EX.path).then(function () { if (EX) { EX.sel = [n]; syncSel(); } }); } });
275
+ });
276
+ }
277
+ function moveInto(paths, dest) {
278
+ var jobs = paths.map(function (p) { var n = p.slice(p.lastIndexOf('/') + 1); return {from: p, to: join(dest, n)}; }).filter(function (j) { return j.from !== j.to && parentOf(j.from) !== dest; });
279
+ if (!jobs.length) return;
280
+ Promise.all(jobs.map(function (j) { return fs('POST', '/api/fs/rename', j); })).then(function (rs) {
281
+ var bad = rs.filter(function (r) { return r.status !== 200; })[0]; if (bad) ck.toast(bad.body.error || 'Could not move.'); else ck.toast('Moved to ' + (dest || wsName()));
282
+ if (EX) { EX.sel = []; EX.prev = null; renderPrev(); load(EX.path); }
283
+ });
284
+ }
285
+ function trash(items) {
286
+ if (!items.length) return;
287
+ var one = items.length === 1, label = one ? '“' + items[0].name + '”' : items.length + ' items';
288
+ askConfirm({title: 'Move to trash', text: 'Move ' + label + ' to the trash?', hint: 'Nothing is deleted for good: the ' + (one ? (items[0].dir ? 'folder' : 'file') : 'items') + ' will be kept in the .ckit/trash folder of this workspace, where you can get ' + (one ? 'it' : 'them') + ' back.', okText: 'Move to trash'}).then(function (ok) {
289
+ if (!ok || !EX) return; var base = EX.path;
290
+ Promise.all(items.map(function (e) { return fs('POST', '/api/fs/delete', {path: join(base, e.name)}); })).then(function (rs) {
291
+ var bad = rs.filter(function (r) { return r.status !== 200; })[0]; ck.toast(bad ? (bad.body.error || 'Could not move to trash.') : 'Moved to trash (.ckit/trash). Nothing was deleted for good.');
292
+ if (EX) { EX.sel = []; EX.prev = null; renderPrev(); load(EX.path); EX.el.rows.focus(); }
293
+ });
294
+ });
295
+ }
296
+
297
+ /* ---------- upload ---------- */
298
+ function upload(files, dir) {
299
+ Array.prototype.forEach.call(files || [], function (f) {
300
+ var u = {name: f.name || 'file', size: f.size, pct: 0, state: 'up', dir: dir};
301
+ EX.uploads.push(u); renderUps();
302
+ var x = new XMLHttpRequest(), my = EX;
303
+ x.open('POST', '/api/fs/upload?path=' + encodeURIComponent(dir) + '&name=' + encodeURIComponent(u.name)); x.setRequestHeader('x-ckit-token', TOKEN); x.setRequestHeader('content-type', 'application/octet-stream');
304
+ x.upload.onprogress = function (ev) { if (ev.lengthComputable) { u.pct = Math.round(ev.loaded / ev.total * 100); renderUps(); } };
305
+ x.onload = function () {
306
+ var j = {}; try { j = JSON.parse(x.responseText); } catch (e) { /* not json */ }
307
+ if (x.status === 200) { u.state = 'ok'; u.pct = 100; u.final = j.name; u.renamed = j.renamed; } else { u.state = 'bad'; u.error = j.error || 'Upload failed.'; }
308
+ finishUp(my, u);
309
+ };
310
+ x.onerror = function () { u.state = 'bad'; u.error = 'Cannot reach CKit; check that ckit is still running.'; finishUp(my, u); };
311
+ x.send(f);
312
+ });
313
+ }
314
+ function finishUp(my, u) {
315
+ if (EX !== my) return; renderUps();
316
+ if (u.state === 'ok') { setTimeout(function () { if (EX === my) { my.uploads = my.uploads.filter(function (x) { return x !== u; }); renderUps(); } }, 6000); if (u.dir === my.path) load(my.path); }
317
+ }
318
+ function renderUps() {
319
+ var box = EX.el.ups; box.innerHTML = ''; box.hidden = !EX.uploads.length;
320
+ EX.uploads.forEach(function (u) {
321
+ var st = u.state === 'bad' ? u.error : u.state === 'ok' ? (u.renamed ? 'saved as “' + u.final + '”' : 'done') : u.pct + '%';
322
+ box.appendChild(h('div', {class: 'exu ' + u.state}, [h('span', {class: 'exun', text: u.name, title: u.name}), h('span', {class: 'exubar'}, [h('i', {style: 'width:' + u.pct + '%'})]), h('span', {class: 'exust', text: st}),
323
+ u.state === 'up' ? null : h('button', {type: 'button', class: 'askx', text: '✕', title: 'Dismiss', onclick: function () { EX.uploads = EX.uploads.filter(function (x) { return x !== u; }); renderUps(); }})]));
324
+ });
325
+ }
326
+ var hasFiles = function (ev) { return ev.dataTransfer && Array.prototype.indexOf.call(ev.dataTransfer.types || [], 'Files') >= 0; };
327
+ var isMove = function (ev) { return ev.dataTransfer && Array.prototype.indexOf.call(ev.dataTransfer.types || [], 'application/x-ckit-move') >= 0; };
328
+ function dropTarget(ev) { var r = ev.target.closest && ev.target.closest('.exitem'); if (!r) return null; var e = byName(r.getAttribute('data-name')); return e && e.dir ? {row: r, e: e} : null; }
329
+ function clearDrop() { var E = EX && EX.el; if (!E) return; E.list.classList.remove('over'); Array.prototype.forEach.call(E.rows.querySelectorAll('.dropto'), function (r) { r.classList.remove('dropto'); }); }
330
+ /* Capture on #modal: files dropped while the explorer is open go to the workspace folder, never to the composer attachments. */
331
+ var M = $('modal');
332
+ M.addEventListener('dragover', function (ev) {
333
+ if (!EX || !(hasFiles(ev) || isMove(ev))) return; ev.preventDefault(); ev.stopPropagation(); clearDrop();
334
+ var inList = EX.el.list.contains(ev.target), t = inList ? dropTarget(ev) : null; ev.dataTransfer.dropEffect = hasFiles(ev) ? 'copy' : 'move';
335
+ if (t) t.row.classList.add('dropto'); else if (inList && hasFiles(ev)) EX.el.list.classList.add('over');
336
+ });
337
+ M.addEventListener('dragleave', function (ev) { if (EX && (!ev.relatedTarget || !M.contains(ev.relatedTarget))) clearDrop(); });
338
+ M.addEventListener('drop', function (ev) {
339
+ if (!EX || !(hasFiles(ev) || isMove(ev))) return; ev.preventDefault(); ev.stopPropagation();
340
+ var t = EX.el.list.contains(ev.target) ? dropTarget(ev) : null; clearDrop(); EX.dragging = false;
341
+ if (isMove(ev) && !hasFiles(ev)) { if (t) { var mv = JSON.parse(ev.dataTransfer.getData('application/x-ckit-move') || '[]').filter(function (p) { return p !== join(EX.path, t.e.name); }); moveInto(mv, join(EX.path, t.e.name)); } return; }
342
+ upload(ev.dataTransfer.files, t ? join(EX.path, t.e.name) : EX.path);
343
+ });
344
+ /* the composer's document-level handlers must not light up behind the popup */
345
+ document.addEventListener('dragover', function (ev) { if (EX && hasFiles(ev)) { var c = $('composer'); c.classList.remove('drop'); } }, true);
346
+
347
+ /* ---------- keyboard ---------- */
348
+ function onKey(ev) {
349
+ if (!EX || document.querySelector('.asklayer')) return;
350
+ var t = ev.target, typing = t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA');
351
+ if (ev.key === 'Escape') {
352
+ ev.stopImmediatePropagation(); ev.preventDefault();
353
+ if (typing && EX.el.filter.value) { EX.el.filter.value = ''; EX.filter = ''; renderList(); } else if (EX.prev) closePrev(); else close();
354
+ return;
355
+ }
356
+ if (typing) { if (ev.key === 'ArrowDown' && t === EX.el.filter) { ev.preventDefault(); EX.el.rows.focus(); } return; }
357
+ if (!EX.el.dlg.contains(t) && t !== document.body) return;
358
+ var list = visible(), names = list.map(function (e) { return e.name; }), at = ev.shiftKey && EX.cursor ? EX.cursor : EX.anchor, cur = at ? names.indexOf(at) : -1, k = ev.key;
359
+ if (k === 'ArrowDown' || k === 'ArrowUp') {
360
+ ev.preventDefault(); if (!names.length) return;
361
+ var i = k === 'ArrowDown' ? Math.min(names.length - 1, cur + 1) : Math.max(0, cur < 0 ? 0 : cur - 1);
362
+ if (ev.shiftKey && EX.anchor && names.indexOf(EX.anchor) >= 0) { var a = names.indexOf(EX.anchor); EX.sel = names.slice(Math.min(a, i), Math.max(a, i) + 1); EX.cursor = names[i]; syncSel(); } else { EX.cursor = null; select(names[i], {}); }
363
+ } else if (k === 'Enter') { var one = EX.sel.length === 1 ? byName(EX.sel[0]) : null; if (one) { ev.preventDefault(); openItem(one); } }
364
+ else if (k === 'Backspace' && (ev.metaKey || ev.ctrlKey)) { ev.preventDefault(); trash(EX.sel.map(byName).filter(Boolean)); }
365
+ else if (k === 'Backspace') { ev.preventDefault(); goUp(); }
366
+ else if (k === 'F2') { var r = EX.sel.length === 1 ? byName(EX.sel[0]) : null; if (r) { ev.preventDefault(); rename(r); } }
367
+ else if (k === 'Delete') { ev.preventDefault(); trash(EX.sel.map(byName).filter(Boolean)); }
368
+ else if ((k === 'a' || k === 'A') && (ev.metaKey || ev.ctrlKey)) { ev.preventDefault(); EX.sel = names; syncSel(); }
369
+ else if (k === 'Home' && names.length) { ev.preventDefault(); select(names[0], {}); } else if (k === 'End' && names.length) { ev.preventDefault(); select(names[names.length - 1], {}); }
370
+ }
371
+
372
+ window.__ckExplorer = {open: open, close: close};
373
+ })();
package/gui/index.html CHANGED
@@ -35,7 +35,7 @@
35
35
  <div class="dh"><span class="ml" id="clabel">OWNER → DIRECTOR</span><span class="ctools"><button class="chip" id="enh" title="Rewrite your request so the Director cannot misread it. You decide whether to use the result.">✦ Enhance</button><button class="chip" id="attach" title="Attach any files: images, PDF, Word, Excel, drawio, XML… You can also drop or paste them here.">📎 Attach files</button></span><input type="file" id="file" multiple hidden></div>
36
36
  <div class="chips" id="chips"></div><div class="chips" id="wbtns" hidden></div><span id="lanewrap" hidden><select id="lane" title="Lane for this request. Auto: the Director decides which lane fits."></select></span>
37
37
  <div class="attlist" id="atts"></div>
38
- <div class="cbox"><textarea id="msg" rows="2" placeholder="Message the Director… (Enter to send)"></textarea><button class="primary" id="send">Send ▸</button></div>
38
+ <div class="cbox"><textarea id="msg" rows="2" placeholder="Message the Director… (Enter to send, @ for a file)"></textarea><button class="primary" id="send">Send ▸</button></div>
39
39
  <div id="cnote"></div>
40
40
  </div>
41
41
  </section>
@@ -47,5 +47,5 @@
47
47
  </div>
48
48
  <div id="modal" hidden></div>
49
49
  <div id="overlay" hidden></div>
50
- <script src="network.js"></script><script src="app.js"></script>
50
+ <script src="network.js"></script><script src="app.js"></script><script src="explorer.js"></script>
51
51
  </body></html>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ngockhoale/ckit",
3
- "version": "0.2.2",
3
+ "version": "0.2.4",
4
4
  "description": "CKit — local Agent Company: a Director plus BA / Implement / QC teams running your own codex, claude and omp CLIs, with a web Mission Control (ckit gui).",
5
5
  "type": "module",
6
6
  "bin": {