@dayzehq/cli 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +305 -2
  3. package/dist/add.d.ts +6 -0
  4. package/dist/add.js +72 -0
  5. package/dist/admin.d.ts +110 -0
  6. package/dist/admin.js +408 -0
  7. package/dist/agent-bridge.d.ts +50 -0
  8. package/dist/agent-bridge.js +146 -0
  9. package/dist/agent-mcp.d.ts +4 -0
  10. package/dist/agent-mcp.js +36 -0
  11. package/dist/ai-consent.d.ts +18 -0
  12. package/dist/ai-consent.js +93 -0
  13. package/dist/args.d.ts +5 -0
  14. package/dist/args.js +127 -0
  15. package/dist/auth.d.ts +20 -0
  16. package/dist/auth.js +198 -0
  17. package/dist/channel.d.ts +55 -0
  18. package/dist/channel.js +250 -0
  19. package/dist/chat.d.ts +67 -0
  20. package/dist/chat.js +170 -0
  21. package/dist/cli-errors.d.ts +13 -0
  22. package/dist/cli-errors.js +30 -0
  23. package/dist/coding-context.d.ts +12 -0
  24. package/dist/coding-context.js +130 -0
  25. package/dist/coding.d.ts +35 -0
  26. package/dist/coding.js +283 -0
  27. package/dist/config.d.ts +36 -0
  28. package/dist/config.js +149 -0
  29. package/dist/day.d.ts +22 -0
  30. package/dist/day.js +54 -0
  31. package/dist/dayze-cli-runtime +0 -0
  32. package/dist/dayze-days.d.ts +56 -0
  33. package/dist/dayze-days.js +276 -0
  34. package/dist/doctor.d.ts +32 -0
  35. package/dist/doctor.js +225 -0
  36. package/dist/focus.d.ts +9 -0
  37. package/dist/focus.js +163 -0
  38. package/dist/index.d.ts +2 -0
  39. package/dist/index.js +675 -0
  40. package/dist/inventory.d.ts +73 -0
  41. package/dist/inventory.js +1272 -0
  42. package/dist/life.d.ts +48 -0
  43. package/dist/life.js +146 -0
  44. package/dist/me.d.ts +94 -0
  45. package/dist/me.js +789 -0
  46. package/dist/people.d.ts +232 -0
  47. package/dist/people.js +2034 -0
  48. package/dist/projects.d.ts +21 -0
  49. package/dist/projects.js +132 -0
  50. package/dist/request-deadline.d.ts +11 -0
  51. package/dist/request-deadline.js +34 -0
  52. package/dist/runtime-build.json +1 -0
  53. package/dist/ui.d.ts +37 -0
  54. package/dist/ui.js +219 -0
  55. package/dist/version.d.ts +4 -0
  56. package/dist/version.js +16 -0
  57. package/package.json +54 -4
@@ -0,0 +1,35 @@
1
+ import { EventEmitter } from 'node:events';
2
+ export declare function runtimeHelper(): string;
3
+ export declare const terminalText: (value: unknown, max?: number) => string;
4
+ type Frame = {
5
+ type: string;
6
+ [key: string]: unknown;
7
+ };
8
+ export declare function contextEnvironment(environment?: NodeJS.ProcessEnv): Array<{
9
+ name: string;
10
+ value: string;
11
+ }>;
12
+ export type CodingOptions = {
13
+ runtime?: string;
14
+ model?: string;
15
+ project: string;
16
+ context: string;
17
+ list?: boolean;
18
+ };
19
+ export declare function parseCodingOptions(args: string[]): CodingOptions;
20
+ /** Sequential host protocol; never auto-retries a prompt with unknown outcome. */
21
+ export declare class CodingConnection extends EventEmitter {
22
+ private child;
23
+ private waiting?;
24
+ private buffer;
25
+ private ended;
26
+ constructor(helper?: string, args?: string[]);
27
+ private consume;
28
+ private finish;
29
+ send(command: Record<string, unknown>): void;
30
+ request(command: Record<string, unknown> | null, type: string, timeout?: number): Promise<Frame>;
31
+ close(): void;
32
+ }
33
+ export declare function listCodingRuntimes(helper?: string): Promise<void>;
34
+ export declare function runCodingSession(options: CodingOptions): Promise<void>;
35
+ export {};
package/dist/coding.js ADDED
@@ -0,0 +1,283 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { spawn } from 'node:child_process';
5
+ import { EventEmitter } from 'node:events';
6
+ import readline from 'node:readline/promises';
7
+ import { stripVTControlCharacters } from 'node:util';
8
+ import { loadCredentials } from './config.js';
9
+ import { contextOwner, parseContext, requireContextConsent } from './coding-context.js';
10
+ import * as ui from './ui.js';
11
+ export function runtimeHelper() {
12
+ const directory = path.dirname(fileURLToPath(import.meta.url));
13
+ const metadata = path.join(directory, 'runtime-build.json');
14
+ if (fs.existsSync(metadata)) {
15
+ const built = JSON.parse(fs.readFileSync(metadata, 'utf8'));
16
+ if (built.platform !== process.platform || built.arch !== process.arch)
17
+ throw new Error('Install a Dayze coding package built for this platform and architecture.');
18
+ }
19
+ return path.join(directory, `dayze-cli-runtime${process.platform === 'win32' ? '.exe' : ''}`);
20
+ }
21
+ export const terminalText = (value, max = 12_000) => stripVTControlCharacters(String(value ?? '')).replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f]/g, '').slice(0, max);
22
+ export function contextEnvironment(environment = process.env) {
23
+ // Desktop deliberately clears the adapter environment. Forward only the CLI
24
+ // connection overrides to this selected MCP child, never the shell environment.
25
+ return ['DAYZE_API_BASE', 'DAYZE_API_KEY', 'DAYZE_CONFIG_DIR'].flatMap(name => environment[name] ? [{ name, value: environment[name] }] : []);
26
+ }
27
+ export function parseCodingOptions(args) {
28
+ const result = { project: process.cwd(), context: 'none' };
29
+ const seen = new Set();
30
+ for (let i = 0; i < args.length; i++) {
31
+ const match = /^--(runtime|model|project|context)(?:=(.*))?$/.exec(args[i]);
32
+ if (!match)
33
+ throw new Error(`Unknown coding option: ${terminalText(args[i])}`);
34
+ const key = match[1];
35
+ if (seen.has(key))
36
+ throw new Error(`Supply --${key} once.`);
37
+ seen.add(key);
38
+ const value = match[2] ?? args[++i];
39
+ if (!value || value.startsWith('--'))
40
+ throw new Error(`--${key} needs a value.`);
41
+ if (key === 'runtime' && !['codex', 'claude'].includes(value))
42
+ throw new Error('Choose --runtime codex or claude.');
43
+ result[key] = value;
44
+ }
45
+ parseContext(result.context);
46
+ result.project = fs.realpathSync(result.project);
47
+ if (!fs.statSync(result.project).isDirectory())
48
+ throw new Error('Choose an existing project directory.');
49
+ return result;
50
+ }
51
+ /** Sequential host protocol; never auto-retries a prompt with unknown outcome. */
52
+ export class CodingConnection extends EventEmitter {
53
+ child;
54
+ waiting;
55
+ buffer = '';
56
+ ended = false;
57
+ constructor(helper = runtimeHelper(), args = []) {
58
+ super();
59
+ this.child = spawn(helper, args, { stdio: 'pipe', shell: false });
60
+ this.child.stdout.setEncoding('utf8');
61
+ this.child.stdout.on('data', (text) => this.consume(text));
62
+ // Provider diagnostics can contain local paths or records. Keep them out of
63
+ // the terminal; the shared engine returns its owner-facing error on stdout.
64
+ this.child.stderr.resume();
65
+ this.child.stdin.on('error', () => this.finish(new Error('Runtime input disconnected.')));
66
+ this.child.on('error', () => this.finish(new Error('Coding runtime could not start. Build/install the Dayze runtime helper first.')));
67
+ this.child.on('close', () => this.finish(new Error('Runtime disconnected. Check the project before repeating the last request.')));
68
+ }
69
+ consume(text) {
70
+ this.buffer += text;
71
+ if (Buffer.byteLength(this.buffer) > 1_048_576) {
72
+ this.close();
73
+ return;
74
+ }
75
+ let end;
76
+ while ((end = this.buffer.indexOf('\n')) >= 0) {
77
+ const line = this.buffer.slice(0, end);
78
+ this.buffer = this.buffer.slice(end + 1);
79
+ let frame;
80
+ try {
81
+ frame = JSON.parse(line);
82
+ if (!frame || typeof frame.type !== 'string')
83
+ throw new Error();
84
+ }
85
+ catch {
86
+ this.finish(new Error('Invalid response from coding runtime.'));
87
+ this.close();
88
+ return;
89
+ }
90
+ if (frame.type === 'error') {
91
+ this.finish(new Error(terminalText(frame.message, 1000)));
92
+ this.close();
93
+ return;
94
+ }
95
+ if (this.waiting?.type === frame.type) {
96
+ const pending = this.waiting;
97
+ this.waiting = undefined;
98
+ clearTimeout(pending.timer);
99
+ pending.resolve(frame);
100
+ }
101
+ else
102
+ this.emit('frame', frame);
103
+ }
104
+ }
105
+ finish(error) {
106
+ this.ended = true;
107
+ if (this.waiting) {
108
+ clearTimeout(this.waiting.timer);
109
+ this.waiting.reject(error);
110
+ this.waiting = undefined;
111
+ }
112
+ }
113
+ send(command) {
114
+ if (!this.ended && this.child.stdin.writable)
115
+ this.child.stdin.write(`${JSON.stringify(command)}\n`, error => { if (error)
116
+ this.finish(new Error('Runtime input disconnected.')); });
117
+ }
118
+ request(command, type, timeout = 120_000) {
119
+ if (this.ended)
120
+ return Promise.reject(new Error('Runtime is closed. Start a new session.'));
121
+ if (this.waiting)
122
+ return Promise.reject(new Error('Wait for the current turn to finish.'));
123
+ return new Promise((resolve, reject) => {
124
+ const timer = setTimeout(() => { this.finish(new Error('Runtime timed out. Check the project before retrying.')); this.close(); }, timeout);
125
+ this.waiting = { type, resolve, reject, timer };
126
+ if (command)
127
+ this.send(command);
128
+ });
129
+ }
130
+ close() {
131
+ this.send({ type: 'close' });
132
+ this.child.stdin.end();
133
+ const kill = setTimeout(() => this.child.kill(), 1000);
134
+ kill.unref();
135
+ this.finish(new Error('Session closed. Check any interrupted action before retrying.'));
136
+ }
137
+ }
138
+ export async function listCodingRuntimes(helper = runtimeHelper()) {
139
+ const connection = new CodingConnection(helper, ['--runtimes']);
140
+ try {
141
+ const frame = await connection.request(null, 'runtimes', 60_000);
142
+ for (const runtime of frame.runtimes) {
143
+ const supported = ['codex', 'claude'].includes(runtime.id);
144
+ console.log(` ${terminalText(runtime.label)} ${supported ? (runtime.connectionInstalled ? terminalText(runtime.auth) : 'connection missing') : 'coding adapter not available'}`);
145
+ }
146
+ }
147
+ finally {
148
+ connection.close();
149
+ }
150
+ }
151
+ export async function runCodingSession(options) {
152
+ if (!process.stdin.isTTY || !process.stdout.isTTY)
153
+ throw new Error('dayze code needs an interactive terminal for tool approvals.');
154
+ if (!fs.existsSync(runtimeHelper()))
155
+ throw new Error('This installation does not include the coding runtime helper. Build it with npm run build:runtime in cli, then install the complete package.');
156
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
157
+ let connection;
158
+ let closed = false;
159
+ let cancelRequested = false;
160
+ const stop = () => { cancelRequested = true; connection?.send({ type: 'cancel' }); connection?.close(); rl.close(); };
161
+ rl.on('close', () => { closed = true; connection?.close(); });
162
+ rl.on('SIGINT', stop);
163
+ process.on('SIGTERM', stop);
164
+ try {
165
+ let runtime = options.runtime ?? (await rl.question('Runtime: 1 Codex · 2 Claude Code [1] ')).trim();
166
+ runtime = runtime === '2' ? 'claude' : (!runtime || runtime === '1' ? 'codex' : runtime);
167
+ if (!['codex', 'claude'].includes(runtime))
168
+ throw new Error('Choose codex or claude.');
169
+ const kinds = parseContext(options.context);
170
+ const creds = loadCredentials();
171
+ if (kinds.length) {
172
+ await requireContextConsent(creds);
173
+ const answer = await rl.question(`Share Dayze ${kinds.join(', ')} with ${runtime} for this session? Type yes: `);
174
+ if (answer.trim().toLowerCase() !== 'yes')
175
+ throw new Error('Context sharing was not enabled. Restart with --context none to code without it.');
176
+ }
177
+ const mcp = kinds.length ? [{ name: 'dayze_selected_context', command: process.execPath,
178
+ args: [fileURLToPath(new URL('./index.js', import.meta.url)), 'coding-context', '--selection', kinds.join(','), '--owner', contextOwner(creds)], env: contextEnvironment() }] : [];
179
+ let restart = true;
180
+ while (restart && !closed) {
181
+ restart = false;
182
+ connection = new CodingConnection();
183
+ let models = [];
184
+ let current = '';
185
+ let permissionPending = false;
186
+ connection.on('frame', (frame) => {
187
+ if (frame.type === 'text')
188
+ process.stdout.write(terminalText(frame.text, 1_048_576));
189
+ else if (frame.type === 'status')
190
+ process.stdout.write(`\n ${ui.c.dim(terminalText(frame.text, 300))}\n`);
191
+ else if (frame.type === 'permission') {
192
+ const p = frame.permission;
193
+ const allow = p.options?.find(option => option.kind === 'allow_once');
194
+ const deny = p.options?.find(option => option.kind === 'reject_once');
195
+ if (permissionPending || !p.requestId || !allow || !deny) {
196
+ connection?.close();
197
+ return;
198
+ }
199
+ permissionPending = true;
200
+ console.log(`\n${terminalText(p.title, 500)}\n${terminalText(p.details, 12_000)}\n`);
201
+ void rl.question('Allow this action once? [y/N] ').then(answer => {
202
+ connection?.send({ type: 'decision', request: p.requestId, option: answer.trim().toLowerCase() === 'y' ? allow.optionId : deny.optionId });
203
+ }).catch(() => connection?.close()).finally(() => { permissionPending = false; });
204
+ }
205
+ });
206
+ try {
207
+ const ready = await connection.request({ type: 'start', runtime, project: options.project, mcp_servers: mcp }, 'models');
208
+ models = ready.models;
209
+ current = String(ready.current ?? 'runtime default');
210
+ if (options.model) {
211
+ const selected = await connection.request({ type: 'model', id: options.model }, 'models');
212
+ current = String(selected.current);
213
+ options.model = undefined;
214
+ }
215
+ console.log(`\n${ui.c.brandBold('Dayze Code')} ${terminalText(runtime)} · ${terminalText(current)}\n${terminalText(options.project)}\nContext: ${kinds.join(', ') || 'off'}\n/model · /runtime · /new · /exit · Ctrl+C stops the session\n`);
216
+ while (!closed) {
217
+ const line = (await rl.question('dayze › ')).trim();
218
+ if (!line)
219
+ continue;
220
+ if (line === '/exit')
221
+ return;
222
+ if (line === '/help') {
223
+ console.log('/model [number or id] · /runtime codex|claude · /new · /exit\nRestart with --context to change shared life context.');
224
+ continue;
225
+ }
226
+ if (line === '/model') {
227
+ models.forEach((model, i) => console.log(` ${i + 1} ${terminalText(model.name)} ${terminalText(model.id)}`));
228
+ continue;
229
+ }
230
+ if (line.startsWith('/model ')) {
231
+ const choice = line.slice(7).trim();
232
+ const id = /^\d+$/.test(choice) ? models[Number(choice) - 1]?.id : models.find(model => model.id === choice)?.id;
233
+ if (!id) {
234
+ console.log('Choose a model listed by /model.');
235
+ continue;
236
+ }
237
+ const changed = await connection.request({ type: 'model', id }, 'models');
238
+ current = String(changed.current);
239
+ console.log(`Model: ${terminalText(current)}`);
240
+ continue;
241
+ }
242
+ if (line === '/runtime') {
243
+ console.log(`Current: ${runtime}. Use /runtime codex or /runtime claude. Changing runtimes starts a new session.`);
244
+ continue;
245
+ }
246
+ if (line === '/new' || /^\/runtime (codex|claude)$/.test(line)) {
247
+ if (line.startsWith('/runtime ')) {
248
+ const next = line.slice(9);
249
+ if (kinds.length && (await rl.question(`Share the selected context with ${next}? Type yes: `)).trim().toLowerCase() !== 'yes')
250
+ continue;
251
+ runtime = next;
252
+ }
253
+ restart = true;
254
+ break;
255
+ }
256
+ if (line.startsWith('/')) {
257
+ console.log('Unknown command. Use /help.');
258
+ continue;
259
+ }
260
+ if (line.length > 8000) {
261
+ console.log('Use a message under 8,000 characters.');
262
+ continue;
263
+ }
264
+ await connection.request({ type: 'prompt', text: line }, 'done', 3 * 60 * 60 * 1000);
265
+ console.log('\n');
266
+ }
267
+ }
268
+ catch (error) {
269
+ if (!cancelRequested && !closed)
270
+ throw error;
271
+ }
272
+ finally {
273
+ connection.close();
274
+ connection = undefined;
275
+ }
276
+ }
277
+ }
278
+ finally {
279
+ connection?.close();
280
+ rl.close();
281
+ process.off('SIGTERM', stop);
282
+ }
283
+ }
@@ -0,0 +1,36 @@
1
+ export type DayzeCredentials = {
2
+ apiBase: string;
3
+ supabaseUrl?: string;
4
+ supabaseAnonKey?: string;
5
+ /** Supabase access token */
6
+ accessToken?: string;
7
+ refreshToken?: string;
8
+ /** dayze_k_… API key with actions scope */
9
+ apiKey?: string;
10
+ email?: string;
11
+ userId?: string;
12
+ handle?: string;
13
+ updatedAt?: string;
14
+ };
15
+ /** Production Dayze API — CLI works without a local Next.js server. */
16
+ export declare const DEFAULT_API_BASE = "https://dayze.com";
17
+ export declare function configPath(): string;
18
+ export declare function isLocalApiBase(apiBase: string): boolean;
19
+ export declare function loadCredentials(): DayzeCredentials;
20
+ export declare function saveCredentials(next: DayzeCredentials): void;
21
+ export declare function clearCredentials(): void;
22
+ export declare function authHeader(creds: DayzeCredentials): string | null;
23
+ export declare function isLoggedIn(creds: DayzeCredentials): boolean;
24
+ /** Human-readable network errors (Node's bare "fetch failed" is useless). */
25
+ export declare function formatFetchError(err: unknown, apiBase: string): string;
26
+ /**
27
+ * Probe API. Prefer a host that actually serves /api/cli/*.
28
+ * If saved host is dead or missing CLI routes, try the other of localhost ↔ production.
29
+ */
30
+ export declare function ensureApiReachable(creds: DayzeCredentials, opts?: {
31
+ timeoutMs?: number;
32
+ persist?: boolean;
33
+ }): Promise<{
34
+ creds: DayzeCredentials;
35
+ switched?: string;
36
+ }>;
package/dist/config.js ADDED
@@ -0,0 +1,149 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { CLI_USER_AGENT } from './version.js';
5
+ /** Production Dayze API — CLI works without a local Next.js server. */
6
+ export const DEFAULT_API_BASE = 'https://dayze.com';
7
+ const CONFIG_DIR = path.join(os.homedir(), '.config', 'dayze');
8
+ const CONFIG_PATH = path.join(CONFIG_DIR, 'credentials.json');
9
+ export function configPath() {
10
+ return CONFIG_PATH;
11
+ }
12
+ export function isLocalApiBase(apiBase) {
13
+ try {
14
+ const u = new URL(apiBase);
15
+ return u.hostname === 'localhost' || u.hostname === '127.0.0.1' || u.hostname === '0.0.0.0';
16
+ }
17
+ catch {
18
+ return /localhost|127\.0\.0\.1/.test(apiBase);
19
+ }
20
+ }
21
+ export function loadCredentials() {
22
+ const envBase = process.env.DAYZE_API_BASE?.replace(/\/$/, '');
23
+ const defaults = {
24
+ apiBase: envBase || DEFAULT_API_BASE,
25
+ apiKey: process.env.DAYZE_API_KEY || undefined,
26
+ };
27
+ if (!fs.existsSync(CONFIG_PATH))
28
+ return defaults;
29
+ try {
30
+ const raw = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8'));
31
+ return {
32
+ ...defaults,
33
+ ...raw,
34
+ apiBase: (raw.apiBase || defaults.apiBase).replace(/\/$/, ''),
35
+ apiKey: process.env.DAYZE_API_KEY || raw.apiKey,
36
+ };
37
+ }
38
+ catch {
39
+ return defaults;
40
+ }
41
+ }
42
+ export function saveCredentials(next) {
43
+ fs.mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
44
+ const payload = {
45
+ ...next,
46
+ apiBase: next.apiBase.replace(/\/$/, ''),
47
+ updatedAt: new Date().toISOString(),
48
+ };
49
+ fs.writeFileSync(CONFIG_PATH, JSON.stringify(payload, null, 2), { mode: 0o600 });
50
+ }
51
+ export function clearCredentials() {
52
+ if (fs.existsSync(CONFIG_PATH))
53
+ fs.unlinkSync(CONFIG_PATH);
54
+ }
55
+ export function authHeader(creds) {
56
+ if (creds.apiKey?.startsWith('dayze_k_'))
57
+ return `Bearer ${creds.apiKey}`;
58
+ if (creds.accessToken)
59
+ return `Bearer ${creds.accessToken}`;
60
+ return null;
61
+ }
62
+ export function isLoggedIn(creds) {
63
+ return Boolean(authHeader(creds));
64
+ }
65
+ /** Human-readable network errors (Node's bare "fetch failed" is useless). */
66
+ export function formatFetchError(err, apiBase) {
67
+ const msg = err instanceof Error ? err.message : String(err);
68
+ const cause = err instanceof Error && err.cause instanceof Error
69
+ ? err.cause.message
70
+ : err instanceof Error && err.cause
71
+ ? String(err.cause)
72
+ : '';
73
+ const blob = `${msg} ${cause}`.toLowerCase();
74
+ if (blob.includes('fetch failed') ||
75
+ blob.includes('econnrefused') ||
76
+ blob.includes('enotfound') ||
77
+ blob.includes('network') ||
78
+ blob.includes('aggregateerror')) {
79
+ if (isLocalApiBase(apiBase)) {
80
+ return (`Cannot reach ${apiBase} (nothing listening).\n` +
81
+ ` Fix: run Next locally → cd dayze-webapp-main && npm run dev\n` +
82
+ ` Or use cloud Dayze → dayze login --api https://dayze.com --key 'dayze_k_…'`);
83
+ }
84
+ return (`Cannot reach ${apiBase}.\n` +
85
+ ` Check network / VPN, or try: dayze login --api https://dayze.com`);
86
+ }
87
+ return cause ? `${msg} (${cause})` : msg;
88
+ }
89
+ /**
90
+ * Probe API. Prefer a host that actually serves /api/cli/*.
91
+ * If saved host is dead or missing CLI routes, try the other of localhost ↔ production.
92
+ */
93
+ export async function ensureApiReachable(creds, opts = {}) {
94
+ const timeoutMs = opts.timeoutMs ?? 2500;
95
+ const persist = opts.persist !== false;
96
+ const LOCAL = 'http://127.0.0.1:3000';
97
+ const probe = async (base) => {
98
+ const ctrl = new AbortController();
99
+ const t = setTimeout(() => ctrl.abort(), timeoutMs);
100
+ try {
101
+ const res = await fetch(`${base.replace(/\/$/, '')}/api/cli/bootstrap`, {
102
+ method: 'GET',
103
+ signal: ctrl.signal,
104
+ headers: { Accept: 'application/json', 'User-Agent': CLI_USER_AGENT },
105
+ });
106
+ const ct = res.headers.get('content-type') || '';
107
+ if (res.status === 404 || ct.includes('text/html'))
108
+ return 'no-cli';
109
+ // 200 / 401 / 500 JSON — host has the CLI route surface
110
+ return 'ok';
111
+ }
112
+ catch {
113
+ return 'down';
114
+ }
115
+ finally {
116
+ clearTimeout(t);
117
+ }
118
+ };
119
+ const base = creds.apiBase.replace(/\/$/, '');
120
+ const primary = await probe(base);
121
+ if (primary === 'ok')
122
+ return { creds };
123
+ const candidates = [];
124
+ if (isLocalApiBase(base)) {
125
+ candidates.push(DEFAULT_API_BASE);
126
+ }
127
+ else {
128
+ candidates.push(LOCAL, DEFAULT_API_BASE);
129
+ }
130
+ for (const alt of candidates) {
131
+ if (alt.replace(/\/$/, '') === base)
132
+ continue;
133
+ const status = await probe(alt);
134
+ if (status === 'ok') {
135
+ const next = { ...creds, apiBase: alt.replace(/\/$/, '') };
136
+ if (persist)
137
+ saveCredentials(next);
138
+ return { creds: next, switched: next.apiBase };
139
+ }
140
+ }
141
+ if (primary === 'no-cli') {
142
+ throw new Error(`${base} is up but /api/cli is not deployed yet.\n` +
143
+ ` Local fix: cd dayze-webapp-main && npm run dev\n` +
144
+ ` dayze login --api http://127.0.0.1:3000 --key 'dayze_k_…'\n` +
145
+ ` Cloud fix: deploy app/api/cli/* to dayze.com, then:\n` +
146
+ ` dayze login --api https://dayze.com --key 'dayze_k_…'`);
147
+ }
148
+ throw new Error(formatFetchError(new Error('fetch failed'), base));
149
+ }
package/dist/day.d.ts ADDED
@@ -0,0 +1,22 @@
1
+ /**
2
+ * `dayze day` — Day Age from /api/cli/me + local civil math (no Agent / polaris stream).
3
+ * Agent path stays on `dayze day --agent` / `dayze day ask`.
4
+ */
5
+ import { type DayzeCredentials } from './config.js';
6
+ import { type SelfAgentMemory, type SelfProfile } from './me.js';
7
+ export type DayCommandOptions = {
8
+ json?: boolean;
9
+ /** Injected clock for tests. */
10
+ now?: Date;
11
+ };
12
+ export type DayAgeSnapshot = {
13
+ day: number | null;
14
+ birthday: string | null;
15
+ timezone: string | null;
16
+ daysToBirthday: number | null;
17
+ alive: string | null;
18
+ };
19
+ /** Resolve Day N using profile birthday + civil "today" in the profile/agent timezone. */
20
+ export declare function dayAgeSnapshot(profile: SelfProfile, agent?: SelfAgentMemory | null, now?: Date): DayAgeSnapshot;
21
+ export declare function printDayAge(snapshot: DayAgeSnapshot): void;
22
+ export declare function runDayCommand(creds: DayzeCredentials, options?: DayCommandOptions): Promise<DayAgeSnapshot>;
package/dist/day.js ADDED
@@ -0,0 +1,54 @@
1
+ /**
2
+ * `dayze day` — Day Age from /api/cli/me + local civil math (no Agent / polaris stream).
3
+ * Agent path stays on `dayze day --agent` / `dayze day ask`.
4
+ */
5
+ import { printJson } from './cli-errors.js';
6
+ import { dayNumberFromBirthday, daysToNextBirthday, formatDayNumber, formatDaysToBday, formatTimeAlive, timeAliveFromBirth, } from './dayze-days.js';
7
+ import { fetchSelfDossier } from './me.js';
8
+ import * as ui from './ui.js';
9
+ /** Resolve Day N using profile birthday + civil "today" in the profile/agent timezone. */
10
+ export function dayAgeSnapshot(profile, agent = null, now = new Date()) {
11
+ const timezone = (profile.timezone || agent?.timezone || null)?.trim() || null;
12
+ const birthday = profile.birthday ? String(profile.birthday).slice(0, 10) : null;
13
+ const day = dayNumberFromBirthday(birthday, now, timezone);
14
+ const daysToBirthday = daysToNextBirthday(birthday, now, null, timezone);
15
+ const alive = formatTimeAlive(timeAliveFromBirth(birthday, profile.birth_time, {
16
+ timezone,
17
+ now,
18
+ }));
19
+ return { day, birthday, timezone, daysToBirthday, alive };
20
+ }
21
+ export function printDayAge(snapshot) {
22
+ console.log('');
23
+ if (snapshot.day == null) {
24
+ console.log(`${ui.c.bold('Day Age')} ${ui.c.dim('—')}`);
25
+ console.log(ui.c.dim(snapshot.birthday
26
+ ? 'Could not compute Day N from this birthday.'
27
+ : 'No birthday on your profile. Set one: dayze me (e edit) or Settings.'));
28
+ console.log('');
29
+ return;
30
+ }
31
+ console.log(`${ui.c.brandBold('Day')} ${ui.c.brandBold(formatDayNumber(snapshot.day))}`);
32
+ if (snapshot.alive)
33
+ console.log(`${ui.c.dim('Alive')} ${ui.c.brandBold(snapshot.alive)}`);
34
+ if (snapshot.birthday)
35
+ console.log(`${ui.c.dim('Birthday')} ${snapshot.birthday}`);
36
+ if (snapshot.daysToBirthday != null) {
37
+ const label = snapshot.daysToBirthday === 0
38
+ ? ui.c.brandBold('today')
39
+ : `${snapshot.daysToBirthday} day${snapshot.daysToBirthday === 1 ? '' : 's'} (${formatDaysToBday(snapshot.daysToBirthday)})`;
40
+ console.log(`${ui.c.dim('→ Birthday')} ${label}`);
41
+ }
42
+ if (snapshot.timezone)
43
+ console.log(`${ui.c.dim('Timezone')} ${snapshot.timezone}`);
44
+ console.log('');
45
+ }
46
+ export async function runDayCommand(creds, options = {}) {
47
+ const dossier = await fetchSelfDossier(creds);
48
+ const snapshot = dayAgeSnapshot(dossier.profile, dossier.agent, options.now ?? new Date());
49
+ if (options.json)
50
+ printJson(snapshot);
51
+ else
52
+ printDayAge(snapshot);
53
+ return snapshot;
54
+ }
Binary file
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Dayze-native day math for the CLI (mirrors lib/temporal.ts / Home / birthday-precision).
3
+ * Kept local so the CLI package stays dependency-light.
4
+ */
5
+ export type BirthdayPrecision = 'day' | 'month' | 'year';
6
+ export declare function resolveBirthdayPrecision(precision: string | null | undefined): BirthdayPrecision;
7
+ /** Civil YYYY-MM-DD → day age index (birth date = day 0), same as Home / Day Reels. */
8
+ export declare function dayNumberFromBirthday(birthday: string | null | undefined, today?: Date,
9
+ /** When set, "today" is the civil date in this IANA zone (Home counter midnight edge). */
10
+ timeZone?: string | null): number | null;
11
+ /** Days until next birthday (0 = today). Only meaningful when precision is full day. */
12
+ export declare function daysToNextBirthday(birthday: string | null | undefined, today?: Date, precision?: string | null, timeZone?: string | null): number | null;
13
+ export declare function formatDayNumber(n: number | null, approximate?: boolean): string;
14
+ export declare function formatDayNumberForPrecision(birthday: string | null | undefined, precision: string | null | undefined): string;
15
+ export declare function formatBirthdayDisplay(birthday: string | null | undefined, precision: string | null | undefined): string | null;
16
+ /** Compact list cell: today / 3d / 47d */
17
+ export declare function formatDaysToBday(n: number | null): string;
18
+ /**
19
+ * Parse CLI / agent birthday edits: YYYY | YYYY-MM | YYYY-MM-DD
20
+ */
21
+ export declare function normalizeBirthdayInput(raw: string | null | undefined): {
22
+ birthday: string;
23
+ precision: BirthdayPrecision;
24
+ } | null;
25
+ export type BirthTimeParts = {
26
+ h: number;
27
+ m: number;
28
+ s: number;
29
+ };
30
+ export type TimeAlive = {
31
+ days: number;
32
+ hours: number;
33
+ minutes: number;
34
+ seconds: number;
35
+ totalMs: number;
36
+ };
37
+ /** Parse HH:mm or HH:mm:ss (Postgres TIME / profile birth_time). */
38
+ export declare function parseBirthTime(raw: string | null | undefined): BirthTimeParts | null;
39
+ /** Normalize edit input → HH:mm:ss or null to clear. */
40
+ export declare function normalizeBirthTimeInput(raw: string | null | undefined): string | null | undefined;
41
+ /**
42
+ * Civil local parts → Date instant.
43
+ * When `timeZone` is an IANA zone, resolves wall-clock time in that zone; else process local.
44
+ */
45
+ export declare function zonedLocalToDate(y: number, mo: number, d: number, h: number, mi: number, s: number, timeZone?: string | null): Date | null;
46
+ /**
47
+ * Exact elapsed lifetime from birthday + birth time.
48
+ * Requires full-day birthday precision (or null precision). No birth time → null.
49
+ */
50
+ export declare function timeAliveFromBirth(birthday: string | null | undefined, birthTime: string | null | undefined, opts?: {
51
+ timezone?: string | null;
52
+ now?: Date;
53
+ precision?: string | null;
54
+ }): TimeAlive | null;
55
+ /** e.g. 12,919d 14h 7m 33s */
56
+ export declare function formatTimeAlive(parts: TimeAlive | null, approximate?: boolean): string | null;