@dreamlake/dreamlake-cli 0.115.0 → 0.117.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.
@@ -706,6 +706,13 @@ export declare function createApi(transport: Transport): {
706
706
  }) => Promise<import("./skills.js").SkillFileResult>;
707
707
  };
708
708
  projects: (namespace: string) => {
709
+ create: (input: import("./workspace.js").ProjectInput) => Promise<{
710
+ [key: string]: unknown;
711
+ id: string;
712
+ slug?: string;
713
+ visibility?: string;
714
+ accessMode?: import("./project-access.js").ProjectAccessMode;
715
+ }>;
709
716
  grants: (project: string) => Promise<unknown>;
710
717
  grant: (project: string, input: ({
711
718
  granteeSlug: string;
@@ -819,11 +826,15 @@ export declare function createApi(transport: Transport): {
819
826
  update: (id: string, input: Partial<import("./common.js").JsonObject>) => Promise<import("./common.js").Resource>;
820
827
  delete: (id: string) => Promise<unknown>;
821
828
  };
829
+ audience: ({ project }: {
830
+ project: string;
831
+ }) => Promise<import("./project-audience.js").ProjectAudience>;
832
+ access: ({ project }: import("./project-access.js").ProjectAccessTarget) => Promise<import("./project-access.js").ProjectAccess>;
833
+ setAccess: ({ project, accessMode, visibility }: import("./project-access.js").ProjectAccessUpdate) => Promise<import("./project-access.js").ProjectAccess>;
822
834
  list: (query?: import("./common.js").Query) => Promise<{
823
835
  [key: string]: unknown;
824
836
  }>;
825
837
  get: (id: string) => Promise<import("./common.js").Resource>;
826
- create: (input: import("./workspace.js").ProjectInput) => Promise<import("./common.js").Resource>;
827
838
  update: (id: string, input: Partial<import("./workspace.js").ProjectInput>) => Promise<import("./common.js").Resource>;
828
839
  delete: (id: string) => Promise<unknown>;
829
840
  };
@@ -1994,6 +2005,13 @@ export declare function createClient(options: ClientOptions): {
1994
2005
  }) => Promise<import("./skills.js").SkillFileResult>;
1995
2006
  };
1996
2007
  projects: (namespace: string) => {
2008
+ create: (input: import("./workspace.js").ProjectInput) => Promise<{
2009
+ [key: string]: unknown;
2010
+ id: string;
2011
+ slug?: string;
2012
+ visibility?: string;
2013
+ accessMode?: import("./project-access.js").ProjectAccessMode;
2014
+ }>;
1997
2015
  grants: (project: string) => Promise<unknown>;
1998
2016
  grant: (project: string, input: ({
1999
2017
  granteeSlug: string;
@@ -2107,11 +2125,15 @@ export declare function createClient(options: ClientOptions): {
2107
2125
  update: (id: string, input: Partial<import("./common.js").JsonObject>) => Promise<import("./common.js").Resource>;
2108
2126
  delete: (id: string) => Promise<unknown>;
2109
2127
  };
2128
+ audience: ({ project }: {
2129
+ project: string;
2130
+ }) => Promise<import("./project-audience.js").ProjectAudience>;
2131
+ access: ({ project }: import("./project-access.js").ProjectAccessTarget) => Promise<import("./project-access.js").ProjectAccess>;
2132
+ setAccess: ({ project, accessMode, visibility }: import("./project-access.js").ProjectAccessUpdate) => Promise<import("./project-access.js").ProjectAccess>;
2110
2133
  list: (query?: import("./common.js").Query) => Promise<{
2111
2134
  [key: string]: unknown;
2112
2135
  }>;
2113
2136
  get: (id: string) => Promise<import("./common.js").Resource>;
2114
- create: (input: import("./workspace.js").ProjectInput) => Promise<import("./common.js").Resource>;
2115
2137
  update: (id: string, input: Partial<import("./workspace.js").ProjectInput>) => Promise<import("./common.js").Resource>;
2116
2138
  delete: (id: string) => Promise<unknown>;
2117
2139
  };
@@ -2553,3 +2575,5 @@ export * from "./memo-facade.js";
2553
2575
  export type { MemoReadingOptions, MemoReadingPage, MemoFocusedRead, NoteReadingOptions, NoteReadingPage, NoteFocusedRead } from "./memo-reading.js";
2554
2576
  export { lineRange, focusedRead, InvalidLineRange } from "./memo-reading.js";
2555
2577
  export type { HostMovePreview, HostMoveRequest, HostMoveReceipt, HostMoveRetainedSessions, HostMoveRetainedRuns } from "./host-moves.js";
2578
+ export * from "./project-access.js";
2579
+ export * from "./project-audience.js";
package/dist/api/index.js CHANGED
@@ -139,3 +139,5 @@ export * from "./memo-write.js";
139
139
  export { documentEdits, documentInsertion } from "./memo-edits.js";
140
140
  export * from "./memo-facade.js";
141
141
  export { lineRange, focusedRead, InvalidLineRange } from "./memo-reading.js";
142
+ export * from "./project-access.js";
143
+ export * from "./project-audience.js";
@@ -0,0 +1,42 @@
1
+ import { type Transport } from './client.js';
2
+ export type ProjectAccessMode = 'workspace' | 'restricted';
3
+ export type ProjectVisibility = 'private' | 'public';
4
+ export interface ProjectAccess {
5
+ projectId: string;
6
+ namespace: string;
7
+ projectSlug: string;
8
+ accessMode: ProjectAccessMode;
9
+ visibility: ProjectVisibility;
10
+ baseline: {
11
+ orgMembers: 'READ' | null;
12
+ namespaceOwners: 'ADMIN';
13
+ public: 'READ' | null;
14
+ };
15
+ viewerRole: 'READ' | 'WRITE' | 'ADMIN';
16
+ manageGrants: boolean;
17
+ }
18
+ export interface ProjectAccessTarget {
19
+ project: string;
20
+ }
21
+ export interface ProjectAccessUpdate extends ProjectAccessTarget {
22
+ accessMode: ProjectAccessMode;
23
+ /** Explicitly make a public Project private when switching to restricted. */
24
+ visibility?: ProjectVisibility;
25
+ }
26
+ export declare function validateProjectAccess(value: unknown, namespace: string, project: string): ProjectAccess;
27
+ /** Same access endpoint used by the product; authorization remains server-side. */
28
+ export declare function projectAccessApi(t: Transport, namespace: string): {
29
+ access: ({ project }: ProjectAccessTarget) => Promise<ProjectAccess>;
30
+ setAccess: ({ project, accessMode, visibility }: ProjectAccessUpdate) => Promise<ProjectAccess>;
31
+ };
32
+ /** Restricted creation requires advertised atomic server support before POST. */
33
+ export declare function createProjectWithAccess<T extends {
34
+ accessMode?: ProjectAccessMode;
35
+ visibility?: string;
36
+ }>(t: Transport, namespace: string, input: T): Promise<{
37
+ id: string;
38
+ slug?: string;
39
+ visibility?: string;
40
+ accessMode?: ProjectAccessMode;
41
+ [key: string]: unknown;
42
+ }>;
@@ -0,0 +1,67 @@
1
+ import { ApiError, seg } from './client.js';
2
+ export function validateProjectAccess(value, namespace, project) {
3
+ const out = value;
4
+ if (!out || !/^[a-f0-9]{24}$/i.test(out.projectId ?? '') || out.namespace !== namespace ||
5
+ typeof out.projectSlug !== 'string' || !out.projectSlug ||
6
+ (/^[a-f0-9]{24}$/i.test(project) ? out.projectId.toLowerCase() !== project.toLowerCase() : out.projectSlug !== project) ||
7
+ !['workspace', 'restricted'].includes(out.accessMode) || !['private', 'public'].includes(out.visibility) ||
8
+ !['READ', 'WRITE', 'ADMIN'].includes(out.viewerRole) || typeof out.manageGrants !== 'boolean' ||
9
+ !out.baseline || ![null, 'READ'].includes(out.baseline.orgMembers) || out.baseline.namespaceOwners !== 'ADMIN' ||
10
+ out.baseline.public !== (out.visibility === 'public' ? 'READ' : null) ||
11
+ (out.accessMode === 'restricted' && (out.baseline.orgMembers !== null || out.visibility !== 'private'))) {
12
+ throw new ApiError(503, 'project_access_unconfirmed', { namespace, project });
13
+ }
14
+ return out;
15
+ }
16
+ /** Same access endpoint used by the product; authorization remains server-side. */
17
+ export function projectAccessApi(t, namespace) {
18
+ const path = (project) => {
19
+ if (!namespace?.trim() || !project?.trim())
20
+ throw new Error('Explicit namespace and project ID or slug are required');
21
+ return `/namespaces/${seg(namespace)}/projects/${seg(project)}/access`;
22
+ };
23
+ return {
24
+ access: async ({ project }) => validateProjectAccess(await t.request('GET', path(project)), namespace, project),
25
+ setAccess: async ({ project, accessMode, visibility }) => {
26
+ if (!['workspace', 'restricted'].includes(accessMode))
27
+ throw new Error('accessMode must be workspace or restricted');
28
+ if (visibility !== undefined && !['private', 'public'].includes(visibility))
29
+ throw new Error('visibility must be private or public');
30
+ if (accessMode === 'restricted' && visibility === 'public')
31
+ throw new Error('Restricted Projects cannot be public');
32
+ const result = validateProjectAccess(await t.request('PATCH', path(project), {
33
+ json: { accessMode, ...(visibility !== undefined ? { visibility } : {}) },
34
+ }), namespace, project);
35
+ if (result.accessMode !== accessMode || (visibility !== undefined && result.visibility !== visibility))
36
+ throw new ApiError(503, 'project_access_unconfirmed', { namespace, project, outcome: 'unknown' });
37
+ return result;
38
+ },
39
+ };
40
+ }
41
+ /** Restricted creation requires advertised atomic server support before POST. */
42
+ export async function createProjectWithAccess(t, namespace, input) {
43
+ if (input.accessMode !== undefined && !['workspace', 'restricted'].includes(input.accessMode))
44
+ throw new Error('accessMode must be workspace or restricted');
45
+ if (input.accessMode === 'restricted' && input.visibility === 'public')
46
+ throw new Error('Restricted Projects cannot be public');
47
+ const path = `/namespaces/${seg(namespace)}/projects`;
48
+ if (input.accessMode === 'restricted') {
49
+ const listing = await t.request('GET', path, { query: { pageSize: 1 } });
50
+ const policy = listing?.accessPolicy;
51
+ if (policy?.apiVersion !== 1 || policy.atomicCreate !== true || !Array.isArray(policy.modes) || !policy.modes.includes('restricted') || !policy.modes.includes('workspace'))
52
+ throw new ApiError(501, 'PROJECT_ACCESS_UNSUPPORTED', { namespace, outcome: 'not-submitted' });
53
+ }
54
+ let result;
55
+ try {
56
+ result = await t.request('POST', path, { json: input });
57
+ }
58
+ catch (error) {
59
+ // Only the dispatched POST can be uncertain; capability failures above submit nothing.
60
+ if (input.accessMode === 'restricted' && (!(error instanceof ApiError) || error.status >= 500))
61
+ throw new ApiError(503, 'project_creation_unconfirmed', { namespace, outcome: 'unknown' });
62
+ throw error;
63
+ }
64
+ if (input.accessMode === 'restricted' && (!result || !/^[a-f0-9]{24}$/i.test(result.id ?? '') || result.accessMode !== 'restricted' || result.visibility !== 'private'))
65
+ throw new ApiError(503, 'project_creation_unconfirmed', { namespace, projectId: result?.id, outcome: 'unknown' });
66
+ return result;
67
+ }
@@ -0,0 +1,32 @@
1
+ import { type Transport } from './client.js';
2
+ import { type ProjectAccess } from './project-access.js';
3
+ export type ProjectRole = 'READ' | 'WRITE' | 'ADMIN';
4
+ export interface AudienceSource {
5
+ kind: 'owner' | 'workspace' | 'public' | 'user' | 'team';
6
+ role: ProjectRole;
7
+ grantId?: string;
8
+ teamId?: string;
9
+ label?: string;
10
+ }
11
+ export interface AudiencePerson {
12
+ userId: string;
13
+ username: string | null;
14
+ name: string | null;
15
+ effectiveRole: ProjectRole | null;
16
+ sources: AudienceSource[];
17
+ }
18
+ export interface ProjectAudience extends ProjectAccess {
19
+ apiVersion: 1;
20
+ complete: true;
21
+ limit: number;
22
+ people: AudiencePerson[];
23
+ publicAudience: string | null;
24
+ resourceBoundary: string;
25
+ }
26
+ export declare function remainingRole(sources: AudienceSource[], removedGrant?: string): ProjectRole | null;
27
+ export declare function validateProjectAudience(value: unknown, namespace: string, project: string): ProjectAudience;
28
+ export declare function projectAudienceApi(t: Transport, namespace: string): {
29
+ audience: ({ project }: {
30
+ project: string;
31
+ }) => Promise<ProjectAudience>;
32
+ };
@@ -0,0 +1,23 @@
1
+ import { ApiError, seg } from './client.js';
2
+ import { validateProjectAccess } from './project-access.js';
3
+ const id = (value) => typeof value === 'string' && /^[a-f0-9]{24}$/i.test(value);
4
+ const role = (value) => ['READ', 'WRITE', 'ADMIN'].includes(value);
5
+ export function remainingRole(sources, removedGrant) {
6
+ return sources.filter(s => !removedGrant || s.grantId !== removedGrant).reduce((best, s) => !best || ['READ', 'WRITE', 'ADMIN'].indexOf(s.role) > ['READ', 'WRITE', 'ADMIN'].indexOf(best) ? s.role : best, null);
7
+ }
8
+ export function validateProjectAudience(value, namespace, project) {
9
+ validateProjectAccess(value, namespace, project);
10
+ const a = value;
11
+ if (a.apiVersion !== 1 || a.complete !== true || a.viewerRole !== 'ADMIN' || a.manageGrants !== true ||
12
+ !Array.isArray(a.people) || a.people.length > 1000 || new Set(a.people.map(p => p?.userId)).size !== a.people.length ||
13
+ a.people.some(p => !p || !id(p.userId) || !(p.username === null || typeof p.username === 'string') || !(p.name === null || typeof p.name === 'string') ||
14
+ !(p.effectiveRole === null || role(p.effectiveRole)) || !Array.isArray(p.sources) || p.sources.some(s => !s || !['owner', 'workspace', 'public', 'user', 'team'].includes(s.kind) || !role(s.role) ||
15
+ (['user', 'team'].includes(s.kind) && !id(s.grantId)) || (s.kind === 'team' && !id(s.teamId)) ||
16
+ (s.kind === 'owner' && s.role !== 'ADMIN') || (['workspace', 'public'].includes(s.kind) && s.role !== 'READ')) ||
17
+ remainingRole(p.sources) !== p.effectiveRole))
18
+ throw new ApiError(503, 'project_audience_unconfirmed', { namespace, project });
19
+ return a;
20
+ }
21
+ export function projectAudienceApi(t, namespace) {
22
+ return { audience: async ({ project }) => validateProjectAudience(await t.request('GET', `/namespaces/${seg(namespace)}/projects/${seg(project)}/audience`), namespace, project) };
23
+ }
@@ -1,13 +1,22 @@
1
1
  export * from "./bindrs.js";
2
+ import { type ProjectAccessMode } from "./project-access.js";
2
3
  /** Workspace resource APIs. Authentication/ACLs stay in the existing service routes. */
3
4
  import { type Transport } from "./client.js";
4
5
  import { type JsonObject, type Query, type Resource } from "./common.js";
5
6
  export interface ProjectInput {
6
7
  name: string;
8
+ accessMode?: ProjectAccessMode;
7
9
  description?: string;
8
10
  visibility?: "private" | "public" | "team";
9
11
  }
10
12
  export declare function projectsApi(t: Transport, namespace: string): {
13
+ create: (input: ProjectInput) => Promise<{
14
+ [key: string]: unknown;
15
+ id: string;
16
+ slug?: string;
17
+ visibility?: string;
18
+ accessMode?: ProjectAccessMode;
19
+ }>;
11
20
  grants: (project: string) => Promise<unknown>;
12
21
  grant: (project: string, input: ({
13
22
  granteeSlug: string;
@@ -122,11 +131,15 @@ export declare function projectsApi(t: Transport, namespace: string): {
122
131
  update: (id: string, input: Partial<JsonObject>) => Promise<Resource>;
123
132
  delete: (id: string) => Promise<unknown>;
124
133
  };
134
+ audience: ({ project }: {
135
+ project: string;
136
+ }) => Promise<import("./project-audience.js").ProjectAudience>;
137
+ access: ({ project }: import("./project-access.js").ProjectAccessTarget) => Promise<import("./project-access.js").ProjectAccess>;
138
+ setAccess: ({ project, accessMode, visibility }: import("./project-access.js").ProjectAccessUpdate) => Promise<import("./project-access.js").ProjectAccess>;
125
139
  list: (query?: Query) => Promise<{
126
140
  [key: string]: unknown;
127
141
  }>;
128
142
  get: (id: string) => Promise<Resource>;
129
- create: (input: ProjectInput) => Promise<Resource>;
130
143
  update: (id: string, input: Partial<ProjectInput>) => Promise<Resource>;
131
144
  delete: (id: string) => Promise<unknown>;
132
145
  };
@@ -1,5 +1,7 @@
1
+ import { projectAudienceApi } from "./project-audience.js";
1
2
  import { bindrsApi } from "./bindrs.js";
2
3
  export * from "./bindrs.js";
4
+ import { projectAccessApi, createProjectWithAccess } from "./project-access.js";
3
5
  /** Workspace resource APIs. Authentication/ACLs stay in the existing service routes. */
4
6
  import { seg } from "./client.js";
5
7
  import { namespacePath, resourceApi, call, } from "./common.js";
@@ -15,6 +17,9 @@ export function projectsApi(t, namespace) {
15
17
  }
16
18
  return {
17
19
  ...resourceApi(t, base),
20
+ ...projectAccessApi(t, namespace),
21
+ ...projectAudienceApi(t, namespace),
22
+ create: (input) => createProjectWithAccess(t, namespace, input),
18
23
  grants: (project) => call(t, "GET", path(project) + "/grants"),
19
24
  grant: async (project, input) => {
20
25
  await manageGrant(project);
@@ -9,6 +9,7 @@ interface CreateOpts {
9
9
  export declare function runCreateBindr(name: string, opts: CreateOpts): Promise<number>;
10
10
  export declare function runCreateDataset(name: string, opts: CreateOpts): Promise<number>;
11
11
  interface CreateProjectOpts {
12
+ accessMode?: string;
12
13
  namespace?: string;
13
14
  slug?: string;
14
15
  description?: string;
@@ -1,5 +1,8 @@
1
1
  import { bindrsApi, BindrMembersError } from "../../api/bindrs.js";
2
2
  import { createTransport, namespaceSeg, seg } from "../../api/client.js";
3
+ // `dl create bindr|dataset <name> --project <target> ...`.
4
+ import { ApiError } from '../../api/client.js';
5
+ import { createClient } from '../../api/index.js';
3
6
  import { HttpError, requestJson } from "../client.js";
4
7
  import { resolveNamespace, resolveRemote, resolveToken } from "../config.js";
5
8
  import { fail, ok, splitCsv } from "../helpers.js";
@@ -126,6 +129,14 @@ export async function runCreateProject(name, opts) {
126
129
  fail(`--visibility must be 'public' or 'private', got '${opts.visibility}'`);
127
130
  return 1;
128
131
  }
132
+ if (opts.accessMode !== undefined && !['workspace', 'restricted'].includes(opts.accessMode)) {
133
+ fail('--access-mode must be workspace or restricted');
134
+ return 1;
135
+ }
136
+ if (opts.accessMode === 'restricted' && opts.visibility === 'public') {
137
+ fail('Restricted Projects cannot be public');
138
+ return 1;
139
+ }
129
140
  const remote = resolveRemote();
130
141
  const token = resolveToken();
131
142
  if (!token) {
@@ -144,19 +155,25 @@ export async function runCreateProject(name, opts) {
144
155
  body.description = opts.description;
145
156
  if (opts.visibility)
146
157
  body.visibility = opts.visibility;
158
+ if (opts.accessMode !== undefined)
159
+ body.accessMode = opts.accessMode;
147
160
  const tags = splitCsv(opts.tags);
148
161
  if (tags.length)
149
162
  body.tags = tags;
150
163
  let created;
151
164
  try {
152
- created = await requestJson(remote, `/namespaces/${namespace}/projects`, {
153
- method: "POST",
154
- token,
155
- json: body,
156
- });
165
+ created = opts.accessMode === undefined
166
+ ? await requestJson(remote, `/namespaces/${namespaceSeg(namespace)}/projects`, { method: 'POST', token, json: body })
167
+ : await createClient({ remote, token }).projects(namespace).create(body);
157
168
  }
158
169
  catch (err) {
159
- if (err instanceof HttpError && err.status === 409) {
170
+ if (err instanceof ApiError && err.code === 'project_creation_unconfirmed') {
171
+ const createdId = err.body?.projectId;
172
+ const identity = typeof createdId === 'string' && /^[a-f0-9]{24}$/i.test(createdId) ? ` Project ID: ${createdId}.` : '';
173
+ fail(`project_creation_unconfirmed: creation outcome is unknown.${identity} Inspect the same namespace before retrying creation.`);
174
+ return 1;
175
+ }
176
+ if ((err instanceof HttpError || err instanceof ApiError) && err.status === 409) {
160
177
  // Report the server's reason: a 409 here is not always a duplicate
161
178
  // slug. OPERATION_CONFLICT is a write conflict the server gave up on.
162
179
  const transient = err.code === "OPERATION_CONFLICT" || err.message === "(409) OPERATION_CONFLICT";
@@ -165,7 +182,7 @@ export async function runCreateProject(name, opts) {
165
182
  : err.message);
166
183
  return 1;
167
184
  }
168
- if (err instanceof HttpError && err.status === 404) {
185
+ if ((err instanceof HttpError || err instanceof ApiError) && err.status === 404) {
169
186
  fail(`namespace '${namespace}' not found`);
170
187
  return 1;
171
188
  }
@@ -191,6 +208,7 @@ export function registerCreateCommand(program) {
191
208
  .option("--namespace <slug>", "namespace (default: your own)")
192
209
  .option("--slug <slug>", "URL-safe slug (auto-derived from name if omitted)")
193
210
  .option("--visibility <vis>", "'public' or 'private' (default: private)")
211
+ .option("--access-mode <mode>", "workspace or restricted; restricted requires advertised atomic server support")
194
212
  .option("--public", "shortcut for --visibility public")
195
213
  .option("--description <text>", "description")
196
214
  .option("--tags <list>", "comma-separated tags")
@@ -76,6 +76,8 @@ export const helpExamples = {
76
76
  "hosts ssh": "dl hosts ssh geyang/dev/worker --duration 1800",
77
77
  "exec": "dl exec geyang/dev/worker -- uname -a\ndl exec geyang/dev/worker --timeout 30 -- sh -c 'printf \"%s\\n\" \"$HOME\"'",
78
78
  "hosts exec": "dl hosts exec geyang/dev/worker -- python3 -c 'print(\"hello\")'",
79
+ "tmux": "# Create or return to dl-session on this host\ndl tmux geyang/dev/worker\n# A separate named terminal; --sess and --session are interchangeable\ndl tmux geyang/dev/worker --sess work",
80
+ "hosts tmux": "dl hosts tmux geyang/dev/worker --session work",
79
81
  "hosts upgrade": "dl hosts upgrade geyang/dev/worker --nymph-version 0.1.32 --dry-run\ndl hosts upgrade geyang/dev/worker --nymph-version 0.1.32\ndl hosts upgrade 'geyang/lab/*' --nymph-version 0.1.32 --concurrency 4 --max-failures 2\ndl hosts upgrade --all --namespace geyang --nymph-version 0.1.32 --json",
80
82
  "hosts rollback": "dl hosts rollback geyang/dev/worker\ndl hosts rollback geyang/dev/worker --upgrade-id 20261029-001 --json",
81
83
  "hosts move": "dl hosts move HOST_ID --namespace alice --to acme --dry-run --json",
@@ -167,10 +169,14 @@ export const helpExamples = {
167
169
  "create bindr": "# Seed a Bindr with matching episodes without an interactive prompt.\ndl create bindr front-cam --project my-robots --episode \"camera/front/*\" --yes",
168
170
  "project inspect": "dl project inspect research --namespace acme",
169
171
  "project grants": "dl project grants research --namespace acme",
172
+ "project access": "# Inspect current baseline, visibility and your effective authority.\ndl project access research --ns acme --json\n# Remove the workspace-member Read baseline; explicit grants remain.\ndl project access research --ns acme --mode restricted\n# A public Project must become private atomically when restricted.\ndl project access research --ns acme --mode restricted --visibility private\n# Restore the workspace-member baseline; this does not make the Project public.\ndl project access research --ns acme --mode workspace",
173
+ "create project": "dl create project \"Private review\" --namespace acme --access-mode restricted",
170
174
  "project grant": "dl project grant research --namespace acme --user teammate --role WRITE\ndl project grant research --namespace acme --team TEAM_ID --role READ",
171
175
  "project revoke": "dl project grants research --namespace acme\ndl project revoke research GRANT_ID --namespace acme",
172
176
  "project attach": "dl project attach research --namespace acme --type note --resource \"$MEMO_ID\"",
173
177
  "project detach": "dl project detach research --namespace acme --type note --resource \"$MEMO_ID\"",
178
+ "project permissions": "# Choose organization and Project with the keyboard.\ndl project permissions\n# Or select the owning namespace and exact Project up front.\ndl project permissions research --namespace acme",
179
+ "project audience": "dl project audience research --namespace acme --json",
174
180
  "provider create": "dl provider create -n aws-demo --provider aws-jump-worker --json\n# Read the generated AGENT.md and terraform/ENROLLMENT.md.\n# Fill terraform/terraform.tfvars.json and terraform/backend.json explicitly.\ndl provider create -n aws-demo --continue --json",
175
181
  "provider plan": "# Requires the selected backend and authorized AWS read access.\ndl provider plan -n aws-demo --json",
176
182
  "provider machine": "dl provider machine status -n aws-dev --account 123456789012 --json\ndl provider machine start -n aws-dev --account 123456789012 --yes\ndl provider machine terminal -n aws-dev --account 123456789012\ndl provider machine stop -n aws-dev --account 123456789012 --yes",
@@ -100,4 +100,4 @@ export declare const HOST_MATCH_LIMIT = 20;
100
100
  /** The `hosts list` columns for a set of hosts: header row first. */
101
101
  export declare function hostRows(hosts: HostSummary[]): string[][];
102
102
  /** The `hosts list` table restricted to keyword matches, for a terminal reader; `color` adds the highlight. */
103
- export declare function formatHostMatches(result: HostInventory, matches: HostMatches, color: boolean, command?: string, limit?: number): string;
103
+ export declare function formatHostMatches(result: HostInventory, matches: HostMatches, color: boolean, command?: string, limit?: number, suffix?: string): string;
@@ -172,7 +172,7 @@ export function hostRows(hosts) {
172
172
  return [["ID", "NAME", "CATALOG", "CONNECTION"], ...hosts.map(host => [cell(host.id), cell(host.name), cell(host.catalog?.catalogState), hostConnection(host.enrollments)])];
173
173
  }
174
174
  /** The `hosts list` table restricted to keyword matches, for a terminal reader; `color` adds the highlight. */
175
- export function formatHostMatches(result, matches, color, command = "ssh", limit = HOST_MATCH_LIMIT) {
175
+ export function formatHostMatches(result, matches, color, command = "ssh", limit = HOST_MATCH_LIMIT, suffix = "") {
176
176
  const quoted = JSON.stringify(matches.keyword);
177
177
  if (!matches.hosts.length)
178
178
  return `No hosts match ${quoted} in namespace ${result.namespace}. Run dl hosts list --all to see every host.`;
@@ -180,7 +180,7 @@ export function formatHostMatches(result, matches, color, command = "ssh", limit
180
180
  const rows = hostRows(shown);
181
181
  const decorate = (value, row, column) => color && row > 0 && column < 2 ? highlightMatches(value, matches.keyword) : value;
182
182
  const more = matches.hosts.length > shown.length ? ` Showing ${shown.length}; narrow the keyword to see the rest.` : "";
183
- const next = matches.hosts.length === 1 ? `Connect with: dl ${command} ${cell(matches.hosts[0].name)}` : "Connect with the full NAME or ID.";
183
+ const next = matches.hosts.length === 1 ? `Connect with: dl ${command} ${cell(matches.hosts[0].name)}${suffix}` : "Connect with the full NAME or ID.";
184
184
  return [`Hosts matching ${quoted} in namespace ${result.namespace}:`, table(rows, decorate),
185
185
  `${matches.hosts.length} of ${result.total} hosts match.${more} ${next}`].join("\n");
186
186
  }
@@ -10,6 +10,7 @@ export interface PickerIO {
10
10
  columns?: number;
11
11
  };
12
12
  color: boolean;
13
+ suffix?: string;
13
14
  }
14
15
  export interface PickerState {
15
16
  query: string;
@@ -18,7 +19,7 @@ export interface PickerState {
18
19
  /** Matches for what is typed so far; an empty query lists the whole inventory. */
19
20
  export declare function pickerMatches(inventory: HostInventory, query: string): HostMatches;
20
21
  /** One frame of the picker: the command being built, the match table with the cursor row marked, and a count. */
21
- export declare function renderPicker(inventory: HostInventory, selector: string, command: "ssh" | "exec", state: PickerState, color: boolean, limit?: number): string;
22
+ export declare function renderPicker(inventory: HostInventory, selector: string, command: "ssh" | "exec" | "tmux", state: PickerState, color: boolean, limit?: number): string;
22
23
  /** Pure key handling, so the loop and the tests share one definition. */
23
24
  export declare function reducePicker(inventory: HostInventory, state: PickerState, key: string): {
24
25
  state: PickerState;
@@ -31,4 +32,4 @@ export declare function splitKeys(chunk: string): string[];
31
32
  * highlighted; typing filters, Tab completes toward the highlighted host one segment at a time, Enter
32
33
  * resolves to that host's full name, and Esc or Ctrl-C resolves to undefined. Draws on `io.output`.
33
34
  */
34
- export declare function pickHost(inventory: HostInventory, selector: string, command: "ssh" | "exec", io: PickerIO): Promise<string | undefined>;
35
+ export declare function pickHost(inventory: HostInventory, selector: string, command: "ssh" | "exec" | "tmux", io: PickerIO): Promise<string | undefined>;
@@ -92,7 +92,7 @@ export function pickHost(inventory, selector, command, io) {
92
92
  io.input.pause();
93
93
  clear();
94
94
  if (picked !== undefined)
95
- io.output.write(`dl ${command} ${picked}\n`);
95
+ io.output.write(`dl ${command} ${picked}${io.suffix ?? ""}\n`);
96
96
  resolve(picked);
97
97
  };
98
98
  const onData = (chunk) => {
@@ -40,6 +40,7 @@ export interface SshOptions {
40
40
  enrollment?: string;
41
41
  duration?: string;
42
42
  timeout?: string;
43
+ tmuxSession?: string;
43
44
  }
44
45
  export interface SshIO {
45
46
  request: typeof hostRequest;
@@ -51,8 +52,10 @@ export interface SshIO {
51
52
  terminal?: () => boolean;
52
53
  /** Whether a person can also type (stdin is a terminal); only then does the picker replace the static list. */
53
54
  interactive?: () => boolean;
55
+ /** tmux requires terminal input and output, independently of picker availability. */
56
+ tty?: () => boolean;
54
57
  /** The interactive picker: resolves to a full host name, or undefined when the person cancels. */
55
- pick?: (inventory: HostInventory, selector: string, command: 'ssh' | 'exec') => Promise<string | undefined>;
58
+ pick?: (inventory: HostInventory, selector: string, command: 'ssh' | 'exec' | 'tmux', suffix?: string) => Promise<string | undefined>;
56
59
  }
57
60
  export declare const defaultSshIO: SshIO;
58
61
  /** Only a selector that named no host earns suggestions; auth, namespace and transport errors pass through unchanged. */
@@ -63,13 +66,18 @@ export declare function isHostLookupMiss(error: unknown): boolean;
63
66
  */
64
67
  export declare function suggestionInventory(selector: string, opts: SshOptions, io?: SshIO): Promise<HostInventory>;
65
68
  /** The `hosts list` table filtered to the selector's keyword, with every match highlighted, for a terminal reader who cannot type back. */
66
- export declare function suggestHosts(selector: string, opts: SshOptions, command: 'ssh' | 'exec', io?: SshIO): Promise<string>;
69
+ export declare function suggestHosts(selector: string, opts: SshOptions, command: 'ssh' | 'exec' | 'tmux', io?: SshIO): Promise<string>;
67
70
  export declare function chooseSshTarget(targets: SshTarget[], selector: string, opts: SshOptions, argv: string[] | undefined, choose?: SshIO['chooseTarget']): Promise<SshTarget>;
68
71
  export declare function sshPublicKey(value: string): string;
69
72
  export declare function validateSshTarget(t: SshTarget, hostId: string, namespace: string): void;
70
73
  export declare function validateSshSession(s: SshSession, t: SshTarget, previous?: string): string;
71
74
  /** Arguments are quoted individually for the enrolled account's POSIX shell. No implicit shell expansion. */
72
75
  export declare function remoteCommand(argv: string[]): string;
76
+ /** Use the remote login PATH and the same optional systemd scope as browser terminals. */
77
+ export declare function remoteTmuxCommand(session: string): string;
78
+ export declare function runHostTmux(selector: string, opts: SshOptions & {
79
+ session?: string;
80
+ }, io?: SshIO): Promise<number>;
73
81
  /** Bounded nymph-ssh.v1 data/FIN stream. Terminal bytes are never logged or persisted. */
74
82
  export declare class SshRelay extends Duplex {
75
83
  private ws;
@@ -24,7 +24,8 @@ export function busyRetryDelay(attempt, retryAt, now = Date.now()) {
24
24
  export const defaultSshIO = {
25
25
  request: hostRequest, fetch: (...args) => fetch(...args), terminal: () => Boolean(process.stderr.isTTY),
26
26
  interactive: () => Boolean(process.stdin.isTTY && process.stderr.isTTY),
27
- pick: (inventory, selector, command) => pickHost(inventory, selector, command, { input: process.stdin, output: process.stderr, color: !process.env.NO_COLOR }),
27
+ tty: () => Boolean(process.stdin.isTTY && process.stdout.isTTY),
28
+ pick: (inventory, selector, command, suffix) => pickHost(inventory, selector, command, { input: process.stdin, output: process.stderr, color: !process.env.NO_COLOR, suffix }),
28
29
  socket: sshSocket,
29
30
  spawn: args => spawn('ssh', args, { stdio: 'inherit' }),
30
31
  };
@@ -63,7 +64,8 @@ export async function chooseSshTarget(targets, selector, opts, argv, choose) {
63
64
  const options = [opts.namespace ? ['--namespace', opts.namespace] : [],
64
65
  opts.duration ? ['--duration', opts.duration] : [], opts.timeout ? ['--timeout', opts.timeout] : []].flat();
65
66
  const rows = targets.map(t => {
66
- const command = ['dl', argv === undefined ? 'ssh' : 'exec', selector, ...options,
67
+ const command = ['dl', opts.tmuxSession !== undefined ? 'tmux' : argv === undefined ? 'ssh' : 'exec', selector, ...options,
68
+ ...(opts.tmuxSession === undefined ? [] : ['--session', opts.tmuxSession]),
67
69
  '--enrollment', t.enrollmentId, ...(argv === undefined ? [] : ['--', ...argv])];
68
70
  return ` ${label(t)}\n ${command.map(quote).join(' ')}`;
69
71
  });
@@ -115,6 +117,26 @@ export function remoteCommand(argv) {
115
117
  throw new Error('exec requires a bounded command and arguments');
116
118
  return 'exec ' + argv.map(a => "'" + a.replace(/'/g, "'\\''") + "'").join(' ');
117
119
  }
120
+ /** Use the remote login PATH and the same optional systemd scope as browser terminals. */
121
+ export function remoteTmuxCommand(session) {
122
+ if (!/^[A-Za-z0-9_-]{1,64}$/.test(session))
123
+ throw new Error('--session/--sess must be 1–64 letters, digits, underscores or hyphens (a tmux name, not a saved session ID)');
124
+ const script = `s="\${SHELL:-/bin/sh}"
125
+ if ! "$s" -lc 'command -v tmux' >/dev/null 2>&1; then
126
+ printf '%s\\n' 'tmux was not found in the remote login PATH. Install tmux, or use dl ssh with the same host for a plain shell.' >&2
127
+ exit 127
128
+ fi
129
+ r="/run/user/$(id -u)"
130
+ [ -n "$XDG_RUNTIME_DIR" ] || { [ -S "$r/bus" ] && export XDG_RUNTIME_DIR="$r"; }
131
+ if command -v systemd-run >/dev/null 2>&1 && systemd-run --user --scope --quiet --collect true >/dev/null 2>&1; then
132
+ exec systemd-run --user --scope --quiet --collect "$s" -lc 'exec tmux -u new-session -A -s "$1"' dl-tmux "$1"
133
+ fi
134
+ exec "$s" -lc 'exec tmux -u new-session -A -s "$1"' dl-tmux "$1"`;
135
+ return remoteCommand(['/bin/sh', '-c', script, 'dl-tmux', session]);
136
+ }
137
+ export function runHostTmux(selector, opts, io = defaultSshIO) {
138
+ return runHostSsh(selector, { ...opts, tmuxSession: opts.session ?? 'dl-session' }, undefined, io);
139
+ }
118
140
  /** Bounded nymph-ssh.v1 data/FIN stream. Terminal bytes are never logged or persisted. */
119
141
  export class SshRelay extends Duplex {
120
142
  ws;
@@ -161,7 +183,12 @@ export async function runHostSsh(selector, opts, argv, io = defaultSshIO) {
161
183
  throw new Error('Host SSH currently requires Linux or macOS and OpenSSH');
162
184
  if (selector.includes('*'))
163
185
  throw new Error('Select one host, not a wildcard');
164
- const command = argv === undefined ? undefined : remoteCommand(argv);
186
+ const tmux = opts.tmuxSession !== undefined;
187
+ if (tmux && argv !== undefined)
188
+ throw new Error('tmux does not accept a remote command');
189
+ const command = tmux ? remoteTmuxCommand(opts.tmuxSession) : argv === undefined ? undefined : remoteCommand(argv);
190
+ if (tmux && !io.tty?.())
191
+ throw new Error('dl tmux requires an interactive terminal on stdin and stdout; run it in a terminal, or use dl exec for non-interactive commands');
165
192
  const duration = Number(opts.duration ?? 1800), timeout = opts.timeout === undefined ? undefined : Number(opts.timeout);
166
193
  if (!Number.isInteger(duration) || duration < 120 || duration > 1800)
167
194
  throw new Error('--duration must be 120–1800 seconds');
@@ -176,15 +203,16 @@ export async function runHostSsh(selector, opts, argv, io = defaultSshIO) {
176
203
  catch (error) {
177
204
  if (!isHostLookupMiss(error) || !io.terminal?.())
178
205
  throw error;
179
- const command = argv === undefined ? 'ssh' : 'exec';
206
+ const command = tmux ? 'tmux' : argv === undefined ? 'ssh' : 'exec';
207
+ const suffix = tmux ? ` --session ${opts.tmuxSession}` : '';
180
208
  const inventory = await suggestionInventory(selector, opts, io).catch(() => undefined);
181
209
  if (!inventory)
182
210
  throw error;
183
211
  if (!io.interactive?.() || !io.pick) {
184
- throw new Error(`${error instanceof Error ? error.message : 'Host lookup failed'}\n${formatHostMatches(inventory, matchHosts(inventory.hosts, selector), !process.env.NO_COLOR, command)}`);
212
+ throw new Error(`${error instanceof Error ? error.message : 'Host lookup failed'}\n${formatHostMatches(inventory, matchHosts(inventory.hosts, selector), !process.env.NO_COLOR, command, undefined, suffix)}`);
185
213
  }
186
214
  // A person is typing: let them pick the host they meant. Cancelling keeps the original error and exit code.
187
- const picked = await io.pick(inventory, selector, command);
215
+ const picked = await io.pick(inventory, selector, command, suffix);
188
216
  if (picked === undefined)
189
217
  throw error;
190
218
  selector = picked;
@@ -313,7 +341,7 @@ export async function runHostSsh(selector, opts, argv, io = defaultSshIO) {
313
341
  '-o', 'StrictHostKeyChecking=yes', '-o', `UserKnownHostsFile=${knownHosts}`, '-o', 'GlobalKnownHostsFile=/dev/null',
314
342
  '-o', `HostKeyAlias=${alias}`, '-o', 'CheckHostIP=no', '-o', 'ForwardAgent=no', '-o', 'ClearAllForwardings=yes',
315
343
  '-o', 'ControlMaster=no', '-o', 'ProxyCommand=none', '-o', 'ConnectTimeout=15', '-o', 'LogLevel=ERROR',
316
- '-i', key, '-p', String(address.port), '-l', target.username, command === undefined ? '-tt' : '-T', '127.0.0.1', ...(command === undefined ? [] : [command])];
344
+ '-i', key, '-p', String(address.port), '-l', target.username, command === undefined || tmux ? '-tt' : '-T', '127.0.0.1', ...(command === undefined ? [] : [command])];
317
345
  child = io.spawn(args);
318
346
  const result = new Promise((resolve, reject) => {
319
347
  child.once('error', () => reject(new Error('Could not start OpenSSH; install ssh and ssh-keygen')));
@@ -348,15 +376,17 @@ export async function runHostSsh(selector, opts, argv, io = defaultSshIO) {
348
376
  }
349
377
  export function registerHostSshCommands(hosts, program) {
350
378
  for (const parent of [hosts, program])
351
- for (const name of ['ssh', 'exec']) {
352
- const c = parent.command(name).description(name === 'ssh' ? 'open a pinned SSH shell through the enrolled Nymph relay' : 'run a command over SSH; stream output and return its exit code')
379
+ for (const name of ['ssh', 'exec', 'tmux']) {
380
+ const c = parent.command(name).description(name === 'tmux' ? 'create or attach to a named remote tmux session through the enrolled SSH relay' : name === 'ssh' ? 'open a pinned SSH shell through the enrolled Nymph relay' : 'run a command over SSH; stream output and return its exit code')
353
381
  .argument('<host>', 'host ID or namespace/group/host[/user]').option('--namespace <slug>').option('--enrollment <id>', 'select an exact SSH enrollment')
354
382
  .option('--duration <seconds>', 'maximum session lifetime (120–1800)', '1800').option('--timeout <seconds>', 'close after this many seconds; does not guarantee detached process termination');
383
+ if (name === 'tmux')
384
+ c.option('--sess, --session <name>', 'remote tmux name; separate from host and saved agent sessions', 'dl-session');
355
385
  if (name === 'exec')
356
386
  c.argument('<command...>', 'command and literal arguments after --');
357
387
  const action = async (selector, opts, args) => {
358
388
  try {
359
- process.exitCode = await runHostSsh(selector, opts, args);
389
+ process.exitCode = await (name === 'tmux' ? runHostTmux(selector, opts) : runHostSsh(selector, opts, args));
360
390
  }
361
391
  catch (e) {
362
392
  console.error(e instanceof Error ? e.message : 'SSH failed');
@@ -0,0 +1,10 @@
1
+ import { type DreamlakeOpts } from '../compat/ctx.js';
2
+ export type ProjectAccessOptions = DreamlakeOpts & {
3
+ namespace?: string;
4
+ ns?: string;
5
+ mode?: string;
6
+ visibility?: string;
7
+ json?: boolean;
8
+ };
9
+ /** Inspect or change only this Project's workspace baseline. No grant/membership changes. */
10
+ export declare function runProjectAccess(project: string, options: ProjectAccessOptions): Promise<number>;
@@ -0,0 +1,43 @@
1
+ import { createClient } from '../../api/index.js';
2
+ import { resolveCtx } from '../compat/ctx.js';
3
+ import { fail } from '../helpers.js';
4
+ import { emitProjectResult } from './output.js';
5
+ /** Inspect or change only this Project's workspace baseline. No grant/membership changes. */
6
+ export async function runProjectAccess(project, options) {
7
+ try {
8
+ const namespace = options.namespace ?? options.ns;
9
+ if (options.namespace && options.ns && options.namespace !== options.ns)
10
+ throw new Error('--namespace and --ns must match');
11
+ if (!namespace?.trim() || !project.trim())
12
+ throw new Error('Explicit namespace and project ID or slug are required');
13
+ if (options.mode !== undefined && !['workspace', 'restricted'].includes(options.mode))
14
+ throw new Error('--mode must be workspace or restricted');
15
+ if (options.visibility !== undefined && !['private', 'public'].includes(options.visibility))
16
+ throw new Error('--visibility must be private or public');
17
+ if (options.visibility !== undefined && options.mode === undefined)
18
+ throw new Error('--visibility requires --mode');
19
+ const ctx = resolveCtx(options);
20
+ if (!ctx.token)
21
+ throw new Error("Not authenticated — run 'dl login' first");
22
+ const api = createClient({ remote: ctx.remote, token: ctx.token }).projects(namespace);
23
+ const result = options.mode === undefined
24
+ ? await api.access({ project })
25
+ : await api.setAccess({ project, accessMode: options.mode,
26
+ ...(options.visibility !== undefined ? { visibility: options.visibility } : {}) });
27
+ emitProjectResult(result, () => [
28
+ `Project: ${result.namespace.replace(/[\x00-\x1f\x7f-\x9f]/g, ' ')}/${result.projectSlug.replace(/[\x00-\x1f\x7f-\x9f]/g, ' ')} (${result.projectId})`,
29
+ `Access mode: ${result.accessMode}`,
30
+ `Visibility: ${result.visibility}`,
31
+ `Workspace members: ${result.baseline.orgMembers ?? 'no baseline'}`,
32
+ `Namespace owners: ${result.baseline.namespaceOwners}`,
33
+ `Public: ${result.baseline.public ?? 'no baseline'}`,
34
+ `Your role: ${result.viewerRole}; manage access: ${result.manageGrants ? 'yes' : 'no'}`,
35
+ 'Direct user/team grants and independent resource access are unchanged.',
36
+ ].join('\n'), options.json);
37
+ return 0;
38
+ }
39
+ catch (error) {
40
+ fail(error.message);
41
+ return 1;
42
+ }
43
+ }
@@ -1,3 +1,5 @@
1
+ import { runProjectPermissions, runProjectAudience } from './permissions.js';
2
+ import { runProjectAccess } from './access.js';
1
3
  import { runProjectAttachment } from './attachments.js';
2
4
  import { runProjectMove } from './move.js';
3
5
  import { runProjectTransferPreview } from './transfer-preview.js';
@@ -32,6 +34,23 @@ export async function runProjectRead(action, project, opts) {
32
34
  }
33
35
  export function registerProjectCommand(program) {
34
36
  const group = program.command('project').description('Inspect or share a Project, or request whole ownership transfer');
37
+ withConnFlags(group.command('permissions [project]'))
38
+ .description('interactive keyboard management of Project audience, grants and access mode')
39
+ .option('--namespace <slug>', 'owning namespace; omit to choose')
40
+ .action(async (project, options) => { process.exitCode = await runProjectPermissions(project, options); });
41
+ withConnFlags(group.command('audience <project>'))
42
+ .description('inspect effective human audience and access sources; requires current ADMIN')
43
+ .requiredOption('--namespace <slug>', 'owning namespace')
44
+ .option('--json', 'emit complete audience snapshot as JSON')
45
+ .action(async (project, options) => { process.exitCode = await runProjectAudience(project, options); });
46
+ withConnFlags(group.command('access <project>'))
47
+ .description('inspect workspace/restricted access, or set it with --mode; requires current project ADMIN for changes')
48
+ .option('--namespace <slug>', 'owning namespace (source context)')
49
+ .option('--ns <slug>', 'alias of --namespace; must match when both are supplied')
50
+ .option('--mode <mode>', 'workspace or restricted; omit to inspect')
51
+ .option('--visibility <visibility>', 'private or public with --mode; use private to restrict a public Project atomically')
52
+ .option('--json', 'print the complete JSON response (automatic when piped)')
53
+ .action(async (project, options) => { process.exitCode = await runProjectAccess(project, options); });
35
54
  withConnFlags(group.command('move <project>'))
36
55
  .description('move a whole Project and its owned Memos, Artifacts and Envs; review and owner acceptance required')
37
56
  .requiredOption('--namespace <slug>', 'current owning namespace')
@@ -0,0 +1,10 @@
1
+ import { type ProjectAudience } from '../../api/index.js';
2
+ import { type DreamlakeOpts } from '../compat/ctx.js';
3
+ type Options = DreamlakeOpts & {
4
+ namespace?: string;
5
+ json?: boolean;
6
+ };
7
+ export declare function audienceText(a: ProjectAudience): string;
8
+ export declare function runProjectAudience(project: string, opts: Options): Promise<number>;
9
+ export declare function runProjectPermissions(project: string | undefined, opts: Options): Promise<number>;
10
+ export {};
@@ -0,0 +1,202 @@
1
+ import { select, input, confirm, search } from '@inquirer/prompts';
2
+ import { createClient, remainingRole } from '../../api/index.js';
3
+ import { resolveCtx } from '../compat/ctx.js';
4
+ import { fail } from '../helpers.js';
5
+ import { emitProjectResult } from './output.js';
6
+ const safe = (s) => String(s ?? '').replace(/[\x00-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069]/g, ' ');
7
+ const out = (s) => process.stderr.write(s + '\n');
8
+ const cancel = '__cancel__';
9
+ const prompts = { input: process.stdin, output: process.stderr };
10
+ const choose = async (message, choices) => select({ message, choices: [...choices, { name: 'Back / cancel', value: cancel }], pageSize: 12 }, prompts);
11
+ const personName = (p) => `${p.username ? '@' + safe(p.username) : safe(p.name)} (${p.userId})`;
12
+ const sourceName = (s) => `${s.kind === 'owner' ? 'namespace owner recovery' : s.kind === 'team' ? `team ${safe(s.label)} (${s.teamId})` : s.kind === 'user' ? 'direct user grant' : s.kind === 'workspace' ? 'organization membership' : 'public'} ${s.role}${s.grantId ? ` [${s.grantId}]` : ''}`;
13
+ export function audienceText(a) {
14
+ const lines = [`Project: ${safe(a.namespace)}/${safe(a.projectSlug)} (${a.projectId})`,
15
+ `Mode: ${a.accessMode} | Visibility: ${a.visibility} | Your role: ${a.viewerRole}`,
16
+ `Organization members: ${a.baseline.orgMembers ?? 'no baseline'} | Owners: ADMIN recovery | Public: ${a.baseline.public ?? 'no baseline'}`,
17
+ 'Effective human audience — current snapshot; memberships can change.'];
18
+ for (const p of a.people)
19
+ lines.push(` ${personName(p)}: ${p.effectiveRole ?? 'no Project access'}\n ${p.sources.map(sourceName).join('; ') || 'No applicable source'}`);
20
+ if (!a.people.length)
21
+ lines.push(' No named active users in this snapshot.');
22
+ if (a.baseline.public)
23
+ lines.push(' Anyone, including anonymous visitors, also has READ. Named users are not the whole public audience.');
24
+ lines.push('Independent resource shares and access through other Projects remain separate.');
25
+ return lines.join('\n');
26
+ }
27
+ function clientFor(opts) {
28
+ const ctx = resolveCtx(opts);
29
+ if (!ctx.token)
30
+ throw new Error("Not authenticated — run 'dl login' first");
31
+ return createClient({ remote: ctx.remote, token: ctx.token });
32
+ }
33
+ export async function runProjectAudience(project, opts) {
34
+ try {
35
+ if (!opts.namespace?.trim())
36
+ throw new Error('Explicit --namespace is required');
37
+ const a = await clientFor(opts).projects(opts.namespace).audience({ project });
38
+ emitProjectResult(a, () => audienceText(a), opts.json);
39
+ return 0;
40
+ }
41
+ catch (e) {
42
+ fail(e.message);
43
+ return 1;
44
+ }
45
+ }
46
+ export async function runProjectPermissions(project, opts) {
47
+ if (!process.stdin.isTTY || !process.stderr.isTTY) {
48
+ fail('Interactive terminal required. Use project audience/grants --json and grant/revoke/access for scripts.');
49
+ return 1;
50
+ }
51
+ let submitted = false;
52
+ try {
53
+ const client = clientFor(opts);
54
+ let namespace = opts.namespace;
55
+ if (!namespace) {
56
+ out('Loading your organizations…');
57
+ const data = await client.organizations.list();
58
+ if (!Array.isArray(data?.myOrganizations))
59
+ throw new Error('Organization list is unconfirmed');
60
+ const choices = data.myOrganizations.map(n => ({ name: `${safe(n.name)} (${safe(n.slug)})`, value: n.slug }));
61
+ const picked = await choose('Choose organization or enter an explicit namespace', [...choices, { name: 'Enter namespace', value: '__enter__' }]);
62
+ if (picked === cancel)
63
+ return 0;
64
+ namespace = picked === '__enter__' ? (await input({ message: 'Exact owning namespace:', validate: s => !!s.trim() || 'Enter a namespace' }, prompts)).trim() : picked;
65
+ }
66
+ const api = client.projects(namespace);
67
+ if (!project) {
68
+ let page = 1;
69
+ while (!project) {
70
+ out(`Loading Projects in ${safe(namespace)}…`);
71
+ const data = await api.list({ page, pageSize: 50 });
72
+ if (!Array.isArray(data.projects))
73
+ throw new Error('Project listing is unconfirmed');
74
+ if (!data.projects.length)
75
+ out('No Projects on this page. Enter a known ID/slug or cancel.');
76
+ const choices = data.projects.map(p => ({ name: `${safe(p.name)} — ${safe(namespace)}/${safe(p.slug)} (${p.id})`, value: p.id }));
77
+ if (data.totalPages && page < data.totalPages)
78
+ choices.push({ name: 'Next page', value: '__next__' });
79
+ if (page > 1)
80
+ choices.push({ name: 'Previous page', value: '__prev__' });
81
+ choices.push({ name: 'Enter exact Project ID or slug', value: '__enter__' });
82
+ const picked = await choose('Choose Project', choices);
83
+ if (picked === cancel)
84
+ return 0;
85
+ if (picked === '__next__') {
86
+ page++;
87
+ continue;
88
+ }
89
+ if (picked === '__prev__') {
90
+ page--;
91
+ continue;
92
+ }
93
+ project = picked === '__enter__' ? (await input({ message: 'Project ID or slug:', validate: s => !!s.trim() || 'Enter a Project' }, prompts)).trim() : picked;
94
+ }
95
+ }
96
+ let projectId = project;
97
+ const load = async () => {
98
+ out('Loading current audience and direct grants…');
99
+ const audience = await api.audience({ project: projectId });
100
+ projectId = audience.projectId; // Subsequent reads/writes bind to the resolved ID, never a reused slug.
101
+ const grants = await api.grants(projectId);
102
+ if (grants?.viewerRole !== 'ADMIN' || !Array.isArray(grants.grants) || !Array.isArray(grants.teams))
103
+ throw new Error('Current grant management contract is unconfirmed');
104
+ return { audience, grants };
105
+ };
106
+ for (;;) {
107
+ const state = await load();
108
+ const { audience: a, grants: g } = state;
109
+ out('\n' + audienceText(a));
110
+ out(`Direct grants: ${g.grants.length}. These alone are not the full audience.`);
111
+ const action = await choose('Project permissions', [
112
+ { name: 'Grant or change a user role', value: 'user' }, { name: 'Grant or change a team role', value: 'team' },
113
+ { name: 'Revoke one direct grant', value: 'revoke' }, { name: 'Set Workspace / Restricted', value: 'mode' },
114
+ { name: 'Refresh audience', value: 'refresh' },
115
+ ]);
116
+ if (action === cancel)
117
+ return 0;
118
+ if (action === 'refresh')
119
+ continue;
120
+ let mutate;
121
+ let verify;
122
+ let preview = '';
123
+ if (action === 'user' || action === 'team') {
124
+ let target;
125
+ if (action === 'user') {
126
+ const choices = a.people.filter(p => p.username).map(p => ({ name: personName(p), value: p.username }));
127
+ target = await search({ message: 'Select a person (type to filter)', pageSize: 10,
128
+ source: term => [...choices.filter(c => c.name.toLowerCase().includes((term ?? '').toLowerCase())),
129
+ { name: 'Enter another exact username', value: '__enter__' }, { name: 'Back / cancel', value: cancel }] }, prompts);
130
+ if (target === '__enter__')
131
+ target = (await input({ message: 'Exact recipient username (without @):', validate: s => /^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(s.trim()) || 'Enter a username, not a name/email' }, prompts)).trim();
132
+ }
133
+ else {
134
+ if (!g.teams.length) {
135
+ out('No active teams are available in this organization. Use a user grant or manage teams separately.');
136
+ continue;
137
+ }
138
+ target = await choose('Select team in this organization', g.teams.map(t => ({ name: `${safe(t.name)} (${safe(t.slug)}; ${t.id})`, value: t.id })));
139
+ }
140
+ if (target === cancel)
141
+ continue;
142
+ const chosenRole = await choose('Role', [{ name: 'READ — read Project content', value: 'READ' }, { name: 'WRITE — read, create and delete content', value: 'WRITE' }, { name: 'ADMIN — also edit Project and manage grants', value: 'ADMIN' }]);
143
+ if (chosenRole === cancel)
144
+ continue;
145
+ const role = chosenRole;
146
+ const body = action === 'user' ? { granteeSlug: target, role } : { teamId: target, role };
147
+ preview = `Set direct ${action} grant: ${safe(target)} → ${role}.\nExisting grant for this recipient is replaced. Other grants and baselines still apply.`;
148
+ mutate = () => api.grant(projectId, body);
149
+ verify = s => s.grants.grants.some(gr => (action === 'user' ? gr.grantee?.slug === target : gr.teamId === target) && gr.role === role);
150
+ }
151
+ else if (action === 'revoke') {
152
+ if (!g.grants.length) {
153
+ out('No direct grants to revoke. Owner recovery and membership/public baselines are controlled separately.');
154
+ continue;
155
+ }
156
+ const id = await choose('Choose exactly one grant to remove', g.grants.map(gr => ({ name: `${safe(gr.grantee?.slug ?? gr.team?.name ?? gr.granteeId ?? gr.teamId)} — ${gr.role} [${gr.id}]`, value: gr.id })));
157
+ if (id === cancel)
158
+ continue;
159
+ const affected = a.people.filter(p => p.sources.some(s => s.grantId === id));
160
+ preview = `Remove direct grant ${id}.\n` + (affected.length ? affected.map(p => `${personName(p)}: ${p.effectiveRole} → ${remainingRole(p.sources, id) ?? 'no Project access'}\n Survives: ${p.sources.filter(s => s.grantId !== id).map(sourceName).join('; ') || 'none'}`).join('\n') : 'No active named users currently receive access through this grant.');
161
+ preview += '\nIndependent resource shares remain. Team membership can change after this snapshot.';
162
+ mutate = () => api.revoke(projectId, id);
163
+ verify = s => !s.grants.grants.some(gr => gr.id === id);
164
+ }
165
+ else {
166
+ const mode = await choose('Access mode', [{ name: 'Restricted — selected user/team grants and namespace owners', value: 'restricted' }, { name: 'Workspace — organization members inherit READ', value: 'workspace' }]);
167
+ if (mode === cancel)
168
+ continue;
169
+ preview = mode === 'restricted'
170
+ ? `Set Restricted and private. Remove organization/public baselines. Explicit user/team grants and owner recovery survive.${a.visibility === 'public' ? '\nThis explicitly makes the public Project private in the SAME request.' : ''}`
171
+ : 'Set Workspace. Organization members inherit READ; existing visibility and grants remain.';
172
+ mutate = () => api.setAccess({ project: projectId, accessMode: mode, ...(mode === 'restricted' ? { visibility: 'private' } : {}) });
173
+ verify = s => s.audience.accessMode === mode && (mode !== 'restricted' || s.audience.visibility === 'private');
174
+ }
175
+ out(`\nReview change to ${safe(namespace)}/${safe(a.projectSlug)} (${projectId})\n${preview}`);
176
+ if (!await confirm({ message: 'Apply this change?', default: false }, prompts)) {
177
+ out('Cancelled. No mutation submitted.');
178
+ continue;
179
+ }
180
+ const fresh = await load();
181
+ if (JSON.stringify(fresh) !== JSON.stringify(state)) {
182
+ out('Access changed during review. No mutation submitted; review the refreshed state.');
183
+ continue;
184
+ }
185
+ submitted = true;
186
+ await mutate();
187
+ const after = await load();
188
+ if (!verify(after))
189
+ throw new Error('Mutation receipt did not match the requested change');
190
+ submitted = false;
191
+ out('Change saved and read back.');
192
+ }
193
+ }
194
+ catch (e) {
195
+ if (!submitted && ['ExitPromptError', 'AbortPromptError'].includes(e.name)) {
196
+ out('Cancelled. No pending mutation submitted.');
197
+ return 0;
198
+ }
199
+ fail(`${safe(e.message)}${submitted ? '\nChange outcome is unconfirmed. It may have applied. Inspect current access before retrying; no automatic retry was made.' : '\nNo pending mutation submitted. Compatible audience/access endpoints and current ADMIN are required.'}`);
200
+ return 1;
201
+ }
202
+ }
@@ -1 +1 @@
1
- export declare const VERSION = "0.115.0";
1
+ export declare const VERSION = "0.117.0";
@@ -6,4 +6,4 @@
6
6
  // value means a binary that re-installs the same version forever.
7
7
  //
8
8
  // Editing this by hand does nothing for a release; bump package.json.
9
- export const VERSION = "0.115.0";
9
+ export const VERSION = "0.117.0";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dreamlake/dreamlake-cli",
3
- "version": "0.115.0",
3
+ "version": "0.117.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/dreamlake-ai/dreamlake-cli.git"
@@ -37,13 +37,13 @@
37
37
  "node": ">=18"
38
38
  },
39
39
  "optionalDependencies": {
40
- "@dreamlake/dreamlake-cli-darwin-arm64": "0.115.0",
41
- "@dreamlake/dreamlake-cli-darwin-x64": "0.115.0",
42
- "@dreamlake/dreamlake-cli-linux-x64": "0.115.0",
43
- "@dreamlake/dreamlake-cli-linux-arm64": "0.115.0",
44
- "@dreamlake/dreamlake-cli-linux-x64-musl": "0.115.0",
45
- "@dreamlake/dreamlake-cli-linux-arm64-musl": "0.115.0",
46
- "@dreamlake/dreamlake-cli-win32-x64": "0.115.0",
47
- "@dreamlake/dreamlake-cli-win32-arm64": "0.115.0"
40
+ "@dreamlake/dreamlake-cli-darwin-arm64": "0.117.0",
41
+ "@dreamlake/dreamlake-cli-darwin-x64": "0.117.0",
42
+ "@dreamlake/dreamlake-cli-linux-x64": "0.117.0",
43
+ "@dreamlake/dreamlake-cli-linux-arm64": "0.117.0",
44
+ "@dreamlake/dreamlake-cli-linux-x64-musl": "0.117.0",
45
+ "@dreamlake/dreamlake-cli-linux-arm64-musl": "0.117.0",
46
+ "@dreamlake/dreamlake-cli-win32-x64": "0.117.0",
47
+ "@dreamlake/dreamlake-cli-win32-arm64": "0.117.0"
48
48
  }
49
49
  }