or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

host-client.mdindex.mdinstance-client.mdmanager-client.mdsequence-client.mdtopics.md

instance-client.mddocs/

0

# Instance Control

1

2

The InstanceClient provides comprehensive management of running sequence instances including lifecycle control, streaming I/O, and event handling.

3

4

## Capabilities

5

6

### Instance Client Creation

7

8

Create an InstanceClient for managing a specific running instance.

9

10

```typescript { .api }

11

/**

12

* Creates InstanceClient for a specific instance

13

* @param id - Instance identifier

14

* @param host - ClientProvider (typically HostClient) for API communication

15

* @returns New InstanceClient instance

16

*/

17

class InstanceClient {

18

readonly id: string;

19

20

static from(id: string, host: ClientProvider): InstanceClient;

21

private constructor(id: string, host: ClientProvider);

22

}

23

```

24

25

**Usage Example:**

26

27

```typescript

28

import { HostClient } from "@scramjet/api-client";

29

30

const host = new HostClient("http://localhost:8000/api/v1");

31

const instance = host.getInstanceClient("instance-id");

32

// or

33

const instance = InstanceClient.from("instance-id", host);

34

```

35

36

### Lifecycle Management

37

38

Control instance execution and lifecycle.

39

40

```typescript { .api }

41

/**

42

* Gracefully stops the instance

43

* @param timeout - Maximum time to wait for graceful shutdown (milliseconds)

44

* @param canCallKeepalive - Whether the instance can extend its lifetime

45

* @returns Promise resolving to stop operation result

46

*/

47

stop(

48

timeout: number,

49

canCallKeepalive: boolean

50

): Promise<STHRestAPI.SendStopInstanceResponse>;

51

52

/**

53

* Forcibly kills the instance

54

* @param opts - Kill options

55

* @param opts.removeImmediately - Bypass instance lifetime extension delay

56

* @returns Promise resolving to kill operation result

57

*/

58

kill(opts?: KillMessageData): Promise<STHRestAPI.SendKillInstanceResponse>;

59

60

/**

61

* Gets current instance health status

62

* @returns Promise resolving to health information

63

*/

64

getHealth(): Promise<STHRestAPI.GetHealthResponse>;

65

66

/**

67

* Gets detailed instance information

68

* @returns Promise resolving to instance details

69

*/

70

getInfo(): Promise<STHRestAPI.GetInstanceResponse>;

71

```

72

73

**Usage Examples:**

74

75

```typescript

76

// Graceful shutdown with 10 second timeout

77

await instance.stop(10000, false);

78

79

// Force kill immediately

80

await instance.kill({ removeImmediately: true });

81

82

// Check instance health

83

const health = await instance.getHealth();

84

console.log(`Instance status: ${health.status}`);

85

```

86

87

### Stream I/O Operations

88

89

Send and receive data streams to/from the instance.

90

91

```typescript { .api }

92

/**

93

* Gets an output stream from the instance

94

* @param streamId - Output stream identifier

95

* @returns Promise resolving to readable stream

96

*/

97

getStream(streamId: InstanceOutputStream): ReturnType<HttpClient["getStream"]>;

98

99

/**

100

* Sends data to an instance input stream

101

* @param streamId - Input stream identifier

102

* @param stream - Data to send (stream or string)

103

* @param requestInit - Optional request configuration

104

* @param options - Stream options

105

* @returns Promise resolving to send operation result

106

*/

107

sendStream(

108

streamId: InstanceInputStream,

109

stream: Parameters<HttpClient["sendStream"]>[1] | string,

110

requestInit?: RequestInit,

111

options?: SendStreamOptions

112

): Promise<STHRestAPI.SendStreamResponse>;

113

114

/**

115

* Convenient method to send data to the instance input stream

116

* @param stream - Data to send (stream or string)

117

* @param requestInit - Optional request configuration

118

* @param options - Stream options

119

* @returns Promise resolving to send operation result

120

*/

121

sendInput(

122

stream: Parameters<HttpClient["sendStream"]>[1] | string,

123

requestInit?: RequestInit,

124

options?: SendStreamOptions

125

): Promise<STHRestAPI.SendStreamResponse>;

126

127

/**

128

* Convenient method to send data to the instance stdin

129

* @param stream - Data to send (stream or string)

130

* @returns Promise resolving to send operation result

131

*/

132

sendStdin(stream: Parameters<HttpClient["sendStream"]>[1] | string): Promise<STHRestAPI.SendStreamResponse>;

133

134

/**

135

* Bidirectional stream operation (send and receive simultaneously)

136

* @param stream - Input data stream

137

* @param requestInit - Optional request configuration

138

* @param options - Stream options

139

* @returns Promise resolving to response stream

140

*/

141

inout(

142

stream: Parameters<HttpClient["sendStream"]>[1],

143

requestInit?: RequestInit,

144

options?: SendStreamOptions

145

): Promise<any>;

146

147

/**

148

* Convenient method to get instance log stream

149

* @returns Promise resolving to log stream

150

*/

151

getLogStream(): Promise<Readable>;

152

```

153

154

**Usage Examples:**

155

156

```typescript

157

import { Readable } from "stream";

158

159

// Get instance output and pipe to console

160

const outputStream = await instance.getStream("output");

161

outputStream.pipe(process.stdout);

162

163

// Send string data to instance

164

await instance.sendInput("Hello, World!\n");

165

166

// Send stream data

167

const dataStream = Readable.from(["line 1\n", "line 2\n", "line 3\n"]);

168

await instance.sendStream("input", dataStream);

169

170

// Monitor instance logs

171

const logStream = await instance.getLogStream();

172

logStream.on('data', (chunk) => {

173

console.log('Instance log:', chunk.toString());

174

});

175

176

// Bidirectional communication

177

const inputStream = Readable.from(["query 1\n", "query 2\n"]);

178

const responseStream = await instance.inout(inputStream);

179

responseStream.pipe(process.stdout);

180

```

181

182

### Event Handling

183

184

Send events to instances and receive events from them.

185

186

```typescript { .api }

187

/**

188

* Sends an event to the instance

189

* @param eventName - Name of the event

190

* @param message - Event data/message

191

* @returns Promise resolving to send event result

192

*/

193

sendEvent(eventName: string, message: string): Promise<STHRestAPI.SendEventResponse>;

194

195

/**

196

* Waits for and returns the next occurrence of a specific event

197

* @param eventName - Name of the event to wait for

198

* @returns Promise resolving to event data

199

*/

200

getNextEvent(eventName: string): Promise<STHRestAPI.GetEventResponse>;

201

202

/**

203

* Gets the last data from a specific event (waits if event never fired)

204

* @param eventName - Name of the event

205

* @returns Promise resolving to event data

206

*/

207

getEvent(eventName: string): Promise<STHRestAPI.GetEventResponse>;

208

209

/**

210

* Gets a continuous stream of events of a specific type

211

* @param eventName - Name of the event type

212

* @returns Promise resolving to event stream

213

*/

214

getEventStream(eventName: string): Promise<Readable>;

215

```

216

217

**Usage Examples:**

218

219

```typescript

220

// Send a custom event to the instance

221

await instance.sendEvent("config-update", JSON.stringify({

222

setting: "debug",

223

value: true

224

}));

225

226

// Wait for instance to send a "ready" event

227

const readyEvent = await instance.getNextEvent("ready");

228

console.log("Instance is ready:", readyEvent.data);

229

230

// Monitor progress events

231

const progressStream = await instance.getEventStream("progress");

232

progressStream.on('data', (chunk) => {

233

const event = JSON.parse(chunk.toString());

234

console.log(`Progress: ${event.percentage}%`);

235

});

236

237

// Get last error event

238

try {

239

const lastError = await instance.getEvent("error");

240

console.log("Last error:", lastError.data);

241

} catch (error) {

242

console.log("No error events received yet");

243

}

244

```

245

246

## Stream Types

247

248

```typescript { .api }

249

/**

250

* Valid input stream identifiers for sending data to instances

251

*/

252

type InstanceInputStream = "stdin" | "input";

253

254

/**

255

* Valid output stream identifiers for receiving data from instances

256

*/

257

type InstanceOutputStream = "stdout" | "stderr" | "output" | "log";

258

```

259

260

## Response Types

261

262

```typescript { .api }

263

interface STHRestAPI {

264

SendStopInstanceResponse: {

265

message: string;

266

acknowledged: boolean;

267

};

268

269

SendKillInstanceResponse: {

270

message: string;

271

killed: boolean;

272

};

273

274

SendEventResponse: {

275

eventName: string;

276

message: string;

277

sent: boolean;

278

};

279

280

GetEventResponse: {

281

eventName: string;

282

data: any;

283

timestamp: string;

284

};

285

286

GetHealthResponse: {

287

status: "healthy" | "unhealthy" | "unknown";

288

message?: string;

289

uptime?: number;

290

[key: string]: any;

291

};

292

293

GetInstanceResponse: {

294

id: string;

295

sequence: string;

296

status: "starting" | "running" | "stopping" | "stopped" | "crashed";

297

ports: { [key: string]: number };

298

created: string;

299

started?: string;

300

ended?: string;

301

[key: string]: any;

302

};

303

304

SendStreamResponse: {

305

bytesWritten: number;

306

status: "success" | "error";

307

message?: string;

308

};

309

}

310

311

interface KillMessageData {

312

removeImmediately?: boolean;

313

}

314

315

interface SendStreamOptions {

316

type?: string;

317

end?: boolean;

318

parseResponse?: "json" | "text" | "stream";

319

json?: boolean;

320

parse?: "json" | "text" | "stream";

321

}

322

```

323

324

## Error Handling

325

326

Instance operations may throw various errors. Common error scenarios:

327

328

```typescript

329

try {

330

await instance.stop(5000, false);

331

} catch (error) {

332

if (error.code === 'INSTANCE_NOT_FOUND') {

333

console.log('Instance no longer exists');

334

} else if (error.code === 'STOP_TIMEOUT') {

335

console.log('Instance did not stop gracefully, consider using kill()');

336

} else {

337

console.log('Unexpected error:', error.message);

338

}

339

}

340

```